Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,25 @@ Some notes about using custom scripts:
- Arguments type is inferenced between each phase of the script except the first where is mandatory to distinguish the data type with the flag -dt TYPE or --dtype=TYPE
- If a reduce parameter is given to the script, it will treat only the first line as an execution of the reduction

##### Using modules
Adding the `--module=[MODULE]` flag will allow to import at runtime the module `MODULE`.
For example if we define `--module=numpy` we will be able to use everything inside `numpy` like for example `numpy.random.default_rng().random()` to generate a random number inside our expression.

There is no limit to the number of times you can add `--module=[MODULE]` flag.

A small example:
```bash
lambda -D --dtype=int --module=math "#i+math.pi for #i in #?" 1 2 3 4 5 6 7 9 0
```

will return the output of:

```python
import math
args = [1, 2, 3, 4, 5, 6, 7, 9, 0]
result = [x+math.pi for x in args]
```

---

### How to contribute
Expand Down
30 changes: 21 additions & 9 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from functools import reduce
from pydoc import locate
from typing import Any, TextIO
from importlib import import_module

from src.constants import LIST_SPECIAL_ARG, SCRIPT_SPECIAL_ARG, EXPR_ARGS_REGEX, EXPR_ARGS_INDICATOR, STRING_BLANK, \
VERSION, ERRNO, OPEN_SQUARE_BRACKET, CLOSE_SQUARE_BRACKET, COMMA, NEWLINE
Expand Down Expand Up @@ -43,6 +44,9 @@ def get_current_year():
parser.add_argument('-dt', '--dtype=', dest='dtype', action='store',
default='str', nargs=1,
help='Define the type of the positional arguments, if omitted they will be treated as strings.')
parser.add_argument('-m', '--module=', dest='module', action='append',
nargs='*', type=str,
help='Add module to use it in the expression.')
parser.add_argument('-f', '--filepath=', dest='source', type=FileType('r'),
nargs='?', default=stdin,
help='Define the File from witch to read, each lines will be parsed into a list argument.')
Expand Down Expand Up @@ -148,6 +152,10 @@ def main(argv: list[str]) -> (int, str):
print(f"### PARSED OPTIONS AND ARGUMENTS\n\n{options}\n\n###")
try:
__lambda_expr__ = options.expr[0]
if options.module is not None:
options.module = flatten(options.module)
for m in options.module:
globals()[m] = import_module(m)
res: Any = None
if SCRIPT_SPECIAL_ARG in __lambda_expr__:
res = exec_script(options)
Expand All @@ -161,23 +169,25 @@ def main(argv: list[str]) -> (int, str):
except RuntimeError:
if options.debug:
print_exc()
return ERRNO['Generic Error'], "An unknown error occurred during the execution, please re-run it with -D flag enabled to see what's wrong."
return ERRNO[
'Generic Error'], "An unknown error occurred during the execution, please re-run it with -D flag enabled to see what's wrong."
return 0, None


def flatten(arg_matrix, delimiter=None):
flat_list = []
for row in arg_matrix:
flat_list += row.split(delimiter) if delimiter is not None else row
return flat_list


def lambda_input(options: Namespace):
args: Any
if options.source != stdin:
with open(options.source.name) as file:
options.args = [line.strip() for line in file]
if options.delimiter is not None:
def flatten_concatenation(arg_matrix):
flat_list = []
for row in arg_matrix:
flat_list += row.split(options.delimiter)
return flat_list

options.args = flatten_concatenation(options.args)
options.args = flatten(options.args, options.delimiter)
if options.dtype == 'str':
args = options.args
else:
Expand All @@ -191,7 +201,9 @@ def flatten_concatenation(arg_matrix):
def output(res: Any, out: TextIO):
echo = f"{res}"
if isinstance(res, list):
echo = NEWLINE.join([val.strip() for val in f"{res}".replace(OPEN_SQUARE_BRACKET, STRING_BLANK).replace(CLOSE_SQUARE_BRACKET, STRING_BLANK).split(COMMA)])
echo = NEWLINE.join([val.strip() for val in
f"{res}".replace(OPEN_SQUARE_BRACKET, STRING_BLANK).replace(CLOSE_SQUARE_BRACKET,
STRING_BLANK).split(COMMA)])
if out == stdout:
print(echo)
else:
Expand Down
4 changes: 4 additions & 0 deletions test/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,7 @@ def test_lambda_script():
script = os.path.abspath("./text.lambda")
exit_code, msg = entrypoint(shellsplit(f'lambda -D --dtype=int script::{script} 2 4'))
assert exit_code == 0 and msg is None

def test_import_module():
exit_code, msg = entrypoint(shellsplit(f'-D --dtype=int --module=numpy "#i+numpy.random.default_rng().random() for #i in #?" 1 2 3 4 5 6 7 9 0'))
assert exit_code == 0 and msg is None