"EvArgs" is a Python module designed for value assignment, easy expression parsing, and type casting. It validates values based on defined rules and offers flexible configuration along with custom validation methods.
Project description
EvArgs
Installation
PyPI
$ pip install evargs
or
$ pip3 install evargs
Conda
$ conda install conda-forge::evargs
Requirements
pythonandpipcommand- Python 3.6 or later version.
Features
- It can specify the condition or value-assignment using a simple expression. e.g.
a=1;b>5 - Evaluate assigned values. e.g
evargs.evaluate('a', 1) - Put values. It's available to using
putis without parsing the expression. - Type cast - str, int, round_int, float, bool, complex, Enum class, custom function...
- Type validation - unsigned, number range, alphabet, regex, any other...
- Applying multiple validations.
- Applying Pre-processing method and Post-processing method.
- Get assigned values.
- Make parameter's description.
- Other support methods for value-assignment.
Usage
Basic
from evargs import EvArgs
evargs = EvArgs()
v = evargs.assign(' 1 ', cast=str, trim=True)
v = evargs.assign('1', cast=int, validation=('range', 1, 10))
rules = {'a': {'cast': int}, 'b': {'cast': float}}
values = {'a': '1', 'b': '2.2'}
values = evargs.assign_values(values, rules)
print(values)
evargs.assign('123', cast=int, validation=('range', 1, 150), name='a')
print(evargs.get('a'))
from evargs import ExpEvArgs
evargs = ExpEvArgs()
evargs.initialize({
'a': {'cast': bool},
'b': {'cast': int},
'c': {'cast': int},
'd': {'cast': float, 'default': 3.14},
'e': {'cast': str},
'f': {'cast': int, 'multiple': True},
})
evargs.parse('a=1;b>=5;c=10;d=;e=H2O;f>=5;f<100')
print(evargs.get('a'), evargs.evaluate('a', True))
print(evargs.get('b'), evargs.evaluate('b', 8))
print(evargs.get('c'), evargs.evaluate('c', 10))
print(evargs.get('d'), evargs.evaluate('d', 3.14))
print(evargs.get('e'), evargs.evaluate('e', 'H2O'))
print(evargs.evaluate('f', 50))
Result:
--
True True
True True
10 True
3.14 True
H2O True
Various rules
from evargs import EvArgs
evargs = EvArgs()
evargs.initialize({
'a': {'cast': int, 'list': True},
'b': {'cast': int, 'multiple': True},
'c': {'cast': lambda v: v.upper()},
'd': {'cast': lambda v: v.upper(), 'post_apply': lambda vals: '-'.join(vals)},
'e': {'cast': int, 'validation': ['range', 1, 10]}
})
~ ... ~
print(print(evargs.get_values())
Result:
--
{'a': [25, 80, 443], 'b': [1, 6], 'c': 'TCP', 'd': 'X-Y-Z', 'e': 5}
evargs.assign(v, cast=ColorEnum, default=ColorEnum.RED)
evargs.assign(v, cast=('enum_value', ColorEnum), required=True)
evargs.assign(1, cast=int, choices=ColorEnum)
Overview
There are 4 way methods in EvArgs. In each 4 way methods, it's available for "type-cast and validation" on rule option.
a. Assign the value
Assigning the value. assign method's arguments is rule options. It's available to use type-cast, validation, any other features.
v = evargs.assign(' 1 ', cast=str, trim=True)
v = evargs.assign('1', cast=int, validation=('range', 1, 10))
v = evargs.assign_values({'a': {'cast': int}, 'b': {'cast': int}}, {'a': '1', 'b': '2'})
evargs.assign('1.5', cast=float, name='var1')
print(evargs.get('var1'))
b. Put the value & Get the value
Putting the value, and get the value. The value is processed by rules, therefore it is not a simple setting.
evargs.initialize({
'a': {'cast': int, validation='unsigned'},
'b': {'cast': float, 'validation': ('range', 1, 10)}
});
evargs.put('a', 1)
evargs.put_values({...})
a = evargs.get('a')
c. Parse the expression & Get the value [ExpEvArgs]
Parsing the expression, and get the value. This feature provides for dynamic value assign.
[Expression]
evargs.parse('a = 1;')
[Get]
a = evargs.get('a')
d. Parse the expression & Evaluate [ExpEvArgs]
Parsing the expression, and evaluate the value. This feature provides for dynamic value assign and value evaluation.
[Expression]
evargs.parse('a >= 1; a<=10')
[Evaluate]
evargs.evaluate('a', 4) --> True
evargs.evaluate('a', 100) --> False
Primary methods of EvArgs
| Method | Description | Doc/Code |
|---|---|---|
initialize |
Initializes rules, default rule, and set options. | doc / code |
set_options |
Set options. | doc / code |
set_default_rule |
Set the default rule. | doc / code |
create_rule |
Create rule by arguments. The default value is reflected. | doc / code |
set_rule |
Set a rule. | doc / code |
set_rules |
Set the rules. | doc / code |
assign |
Assign a value. If specifying name, the value is stored. |
doc / code |
assign_values |
Assign the values. | doc / code |
get_rule |
Get the rule by each argument. | doc / code |
get_rule_options |
Get the rule's option values. | doc / code |
get |
Get the value of a parameter by name and index. | doc / code |
get_values |
Get the values of parameters. | doc / code |
put |
Put the value. | doc / code |
put_values |
Put the values of parameters. | doc / code |
make_help |
Make parameter's description. Refer to Make help. |
doc / code |
| Other methods | has_param, get_param, get_size, delete, reset ... |
doc / code |
ExpEvArgs
| Method | Description | Doc/Code |
|---|---|---|
parse |
Parse the expression. | doc / code |
evaluate |
Evaluate a parameter. | doc / code |
Related
Rule options
The following are the rule options.
| Option name | Type | Default | Description | Code |
|---|---|---|---|---|
cast |
str, callable |
None |
Cast-type (e.g., int, str, bool, float, Enum class, ...). Refer to Type cast. |
code |
required |
bool |
False |
Whether the parameter is required. | code |
default |
any |
None |
Set the default value if the value is not provided. | code |
nullable |
bool |
True |
Allow None value. Also, when casting to int or float, an empty string value is converted to None. |
code |
trim |
bool, str |
None |
Trim the value if it is enabled. bool or str value for trim process. | code |
validation |
str, tuple, list, callable |
None |
Validation name, list of arguments, or a custom validation method. And it's possible to specify multiple validations with tuple. Refer to Value validation. |
code |
choices |
list, tuple, Enum class |
None |
Restrict the value to predefined values. | code |
pre_cast |
callable |
None |
Pre-casting method for the value. | code |
post_cast |
callable |
None |
Post-casting method for the value. | code |
pre_apply |
callable |
None |
Pre-processing method for the parameter before applying. | code |
post_apply |
callable, str, tuple, list |
None |
Post-processing method for the parameter after applying. Validation method can also be specified. And it's possible to specify multiple regulations with tuple. | code |
raise_error |
int [0, 1, 2] |
1 |
Raise an error during casting.0: Cancel error1: Raise error if default is none2: Raise all error |
code |
list |
bool |
False |
The value is list value if it is enabled. | code |
multiple |
bool |
False |
Allow multiple values. | code |
help |
str, tuple/list |
None |
Description for the value. | code |
There is also a description about
The order of value processingin a later section.
ExpEvArgs
| Option name | Type | Default | Description | Code |
|---|---|---|---|---|
evaluation |
callable |
None |
Evaluation method for the value. | code |
evaluation_apply |
callable |
None |
Evaluation method for the parameter. | code |
multiple_or |
bool |
False |
Whether to use logical OR for multiple condition values. | code |
list_or |
bool |
None |
Whether to use logical OR for list values. Adjusts automatically by operator if the value is None. | code |
Example
evargs.assign(v, cast=str, list=True)
evargs.assign(v, cast=int, multiple=True)
evargs.assign(v, pre_cast=lambda v: v.upper())
evargs.initialize({
'a': {'cast': str, 'list': True},
'b': {'cast': int, 'multiple': True},
'c': {'pre_cast': lambda v: v.upper()},
})
evargs.set_rules({
'a': {'cast': str, 'list': True},
'b': {'cast': int, 'multiple': True},
'c': {'pre_cast': lambda v: v.upper()},
})
Type cast
| Type cast | Description | Doc/Code |
|---|---|---|
int, 'int' |
Casting to int. | doc / code |
'round_int' |
Casting to int with round. | doc / code |
float, 'float' |
Casting to float. | doc / code |
complex, 'complex' |
Casting to complex. | doc / code |
bool, 'bool' |
Casting to bool. | doc / code |
'bool_strict' |
Casting to bool strictly. | doc / code |
'bool_loose' |
Casting to bool loosely. | doc / code |
str, 'str' |
Casting to str. | doc / code |
Enum class |
Casting to Enum class. | doc / code |
('enum', Enum class) |
Casting to Enum class by Enum's name or Enum's value. | doc / code |
('enum_value', Enum class) |
Casting to Enum class by Enum's value. | doc / code |
('enum_name', Enum class) |
Casting to Enum class by Enum's name. | doc / code |
'raw' |
The casting process is not be executed. | - |
callable |
Custom callable function for casting. e.g. lambda v: v.upper() |
- |
Related
Value validation
In the value validation, required option is available to checking for the value existence and choices option is available to restricting the value. Additionally, you can use the following validation rules or custom function in validation option.
Validations
| Name | Value Type | Description | Doc/Code |
|---|---|---|---|
exist |
any |
The value is exist. | doc / code |
size |
any |
The value length is exactly size. |
doc / code |
sizes |
any |
The value length is sizes min_size and max_size. |
doc / code |
enum |
any |
The value is enum class's value. | doc / code |
alphabet |
str |
Alphabetic characters. | doc / code |
alphanumeric |
str |
Alphanumeric characters. | doc / code |
ascii |
str |
ASCII characters. | doc / code |
printable_ascii |
str |
Printable ASCII characters. | doc / code |
standard_ascii |
str |
Standard ASCII characters. | doc / code |
char_numeric |
str |
Numeric characters. | doc / code |
regex |
str |
The string matches the regular expression. | doc / code |
range |
int, float |
The numeric value is within range min_v to max_v. |
doc / code |
unsigned |
int, float |
Unsigned number. | doc / code |
positive |
int, float |
Positive number. | doc / code |
negative |
int, float |
Negative number. | doc / code |
even |
int |
Even int. | doc / code |
odd |
int |
Odd int. | doc / code |
Format of validation and post_apply
# Single validation
'validation': 'validation_name' # No parameter - str
'validation': function # callable
'validation': ('validation_name', param1, param2...) - tuple
'validation': ['validation_name', param1, param2...] - list
# Multiple validations
'validation': [('validation_name',), ('validation_name', 4)] - list -> tuple, tuple
'validation': [tuple(['validation_name']), ('validation_name', 4), function] - list -> tuple, tuple, callable
e.g.
evargs.assign(v, cast=int, choices=[1, 2, 3])
evargs.assign(v, cast=int, choices=EnumClass)
evargs.assign(v, cast=str, validation=('size', 3))
evargs.assign(v, cast=str, validation=('sizes', 4, 10))
evargs.assign(v, cast=str, validation='alphabet')
evargs.assign(v, cast=int, validation=('range', None, 100))
evargs.assign(v, cast=str, validation=('regex', r'^ABC\d+XYZ$', re.I))
evargs.assign(v, cast=int, validation=lambda n, v: True if v >= 0 else False)
evargs.assign(v, cast=str, validation=[('size', 4), ('alphabet',)])
# Validation in post_apply
evargs.assign(['1', '2', '3'], cast=int, list=True, post_apply='exist')
Related
The order of value processing
This is description of "The order of value processing - Internal specification".
pre_apply: Pre applying. Processing to whole value.trim: Trim if the value is str.pre_cast: Pre casting.cast: Casting.post_cast: Post casting.required: Validating the value exists.validation: Validation.choices: Validating choices.post_apply: Post applying. If validation in post_apply is set, validating whole value.
If list mode is enabled in the rule options, processing for "each value" in [trim - choices].
Description of options
flexible=True
It can be operated even if the rule is not defined.
e.g. specifying flexible=True and default_rule={...}.
required_all=True
All parameters defined in rules must have values assigned. The behavior is equivalent to specifying 'required=True' for each rule.
ignore_unknown=True
Ignoring and excluding the unknown parameter. The error does not occur if the unknown parameter is assigned.
default_rule={...}
Default rule for all parameters. e.g. {'cast': int, 'default': -1}
Make help
make_help method can make parameter's description. get_help_formatter method provide some displaying features.
e.g.
desc = evargs.make_help()
Name | * | e.g. | Validation | Description
---------------------------------------------------------------------------------------
planet_name | Y | Jupiter | | Name of the planet.
distance_from_sun | N | | unsigned | Distance from the Sun in kilometers.
diameter | N | 6779 | customize | Diameter of the planet in kilometers.
has_water | N | 1 | | Indicates if the planet has water.
surface_color | N | Black | | Main color of the surface.
help_formatter = evargs.get_help_formatter()
help_formatter.set_columns({
'name': 'Name',
'required': '*',
'cast': 'Type cast',
'help': 'Desc'
})
Also ListFormatter class can also be used independently to adjust and display dict and list data. The example is here.
# python3 show_list_data.py
Compound Name | Elements | Molecular Formula | Melting Point | Uses
--------------------------------------------------------------------------------------------------------------------------
Aspirin | Carbon (C), Hydrogen (H), Oxygen (O) | C9H8O4 | 135°C | Pain reliever
Glucose | Carbon (C), Hydrogen (H), Oxygen (O) | C6H12O6 | 146°C | Energy source
Acetaminophen | Carbon (C), Hydrogen (H), Nitrogen (N), Oxygen (O) | C8H9NO | 169-172°C | Pain reliever
Niacin | Carbon (C), Hydrogen (H), Nitrogen (N) | C6H5NO2 | 234-236°C | Nutrient
Salicylic Acid | Carbon (C), Hydrogen (H), Oxygen (O) | C7H6O3 | 158-160°C | Preservative
Related
Examples and Test code
Examples
There are some examples in ./examples/.
Test code
There are many examples in ./tests/.
| File | Description |
|---|---|
| test_assign.py | Tests for assigning parameters and parsing values. |
| test_general.py | General tests for EvArgs. |
| test_options.py | Tests for options of flexible, required_all, ignore_unknown, and set_options. |
| test_error.py | Tests for error handling in EvArgs. |
| test_exception.py | Tests specific exceptions raised by invalid inputs in EvArgs. |
| test_get_put.py | Tests for get and put methods. |
| test_rule_validation.py | Tests for rule validation, including validation, and custom validation methods. |
| test_rule_choices.py | Tests for choices. |
| test_rule_cast.py | Tests for type handling in rules, such as int, float, bool, str, complex, Enum class and custom types. |
| test_rule_cast_enum.py | Tests for Enum type in rules. |
| test_rule_required_default.py | Tests for required and default options. |
| test_rule_pre_post.py | Tests for pre_cast and post_cast for value transformations. |
| test_rule_multiple.py | Tests for multiple option in rules. |
| test_exp_general.py | Tests for ExpEvArgs including general usages. |
| test_exp_evaluate.py | Tests for ExpEvArgs and including evaluate. |
| test_exp_multiple.py | Tests for ExpEvArgs including evaluate and multiple. |
| test_show_help.py | Tests for showing help. |
| test_list_formatter.py | Tests for HelpFormatter, ListFormatter class. |
| test_type_cast.py | Tests for TypeCast class. |
| test_validator.py | Tests for Validator class. |
| test_helper.py | Tests for ExpressionParser. |
Class docs
- EvArgs class
- Validator class
- TypeCast class
- HelpFormatter class
- ListFormatter class
- EvArgsException class / ValidateException class
Dependencies
No dependency.
Other OSS
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file evargs-1.0.0b1.tar.gz.
File metadata
- Download URL: evargs-1.0.0b1.tar.gz
- Upload date:
- Size: 43.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8cb426d8db6d109d5573e1a81fdaf5c2664d050b28c8804253530d53f1f7055d
|
|
| MD5 |
cea1f7da3fc4103e44eea828af62a9b6
|
|
| BLAKE2b-256 |
aa88fc1bcef4c69a44278b78b7cae238b5f44627e60d1d37ddf516d6cc658c7c
|
File details
Details for the file evargs-1.0.0b1-py3-none-any.whl.
File metadata
- Download URL: evargs-1.0.0b1-py3-none-any.whl
- Upload date:
- Size: 21.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a4ac749ea1df2da5fe7453a43aec4e254a321e7028f5c783c70bb5b2bfd42887
|
|
| MD5 |
b80342e731e75a045712916ee2c08c6f
|
|
| BLAKE2b-256 |
88318ba0dc046a4888ae3f8c3c10fba5619af7919b5c1e1de73c536d8d295728
|