A python decorator which checks types & restrictions for user inputs
Project description
Checkout - freepik - the photographer of Mr. Tcheasy & Sorpa!
tcheasy
tcheasy is a python decorator that makes type checking (at runtime) easy!
Just import the decorator and start to check your function inputs from the get-go.
You want to define input restrictions as well? Then your are in the right place!
Python >= 3.8 needed. Tested ver. { 3.8.5, 3.9.9 }
CONTENT
WHY? Back to top
For one of my projects I needed a way to check user inputs at runtime.
There were already packages that do type-checking, but they only use the - relatively simplistic - python type hints.
The problem, however, was that I needed not only type checking but also the option to restrict some parameter inputs.
Enter tcheasy!
Out of the need to have a tool for other projects, this python decorator was born.
This little kritter is able to use a predefined dict or the python type hinting. Please refere to the how? & example? section for more infos about the usage.
tcheasy ships also with his neat little friend sorpa:
The function sorpa() is able to extract and sort your passed function parameters at runtime.
If you are sololy looking for a type checking tool (and some handy utility-tools) you should also check out:
Else feel free to use and modify tcheasy as you please.
HOW? Back to top
Just import the package
from tcheasy import tcheasy
and add the decorator @tcheasy() to your to-be-checked function.
If you are already using python type hinting tcheasy is ready out of the box.
In the current version, the following types (hints) are supported:
- NoneType(s): None
- number types: int, float, complex, bool
- sequence types: str, list, tuple
- mapping types: dict
- set types: sets
- callable types: object
typing-module types: typing.Any, typing.Union
But the true might comes from using declarative dicts.
By passing a dict to @tcheasy() you can specify the parameter types, add rudimentary input restrictions & default values.
The structure of these dictionaries (and their used keywords) is always the same (type, restriction (optional) & default (optional)):
# define the dict!
to_check = {
'positional':{
'parameter-name':{
'type': type,
'restriction': "(optional) in the form: value condition",
'default': "(optional) default value"
},
'next-parameter-name':{
...
},
...
},
'args':[ {'type':type, 'restriction':str, 'default': "value" }, {...}, ...],
'kwargs': {
'parameter-name':{...},
...
}
}
As you can see, you have the complete control over potential *args and **kwargs.
The definition structure of 'kwargs' is also the same as for the positionals.
Keep in mind that you do not have to define restriction and/or default. These two keywords are completely optional.
After you have defined the dict you can pass it to @tcheasy() and it will start to monitor the function at runtime (e.g. if your dict is called to_check, then you pass it like this: @tcheasy(to_check)).
Note:
The separation ofpositional,args&kwargsis derived of the python parameter types. There are 5 distinct types, which can be boiled down to basically 3 'blocks':
- positional:
- keyword parameters (your typical
def test(a), while the call wastest(a='some-value'))- (positional) parameters (again your typical
def test(a)but this time calling justtest('some-value'))- *args:
- arbitrary positional arguments (
def test(a, *args), while callingtest('value-a', 'value-args'))- **kwargs:
- arbitrary keyword arguments (
def test(a, **kwargs), while callingtest('value-a', add_kwargs="some-value"))
The structure of the default keyword is - as mentioned - always the same. For example consider the following:
...
'parameter-name': {
'type': int,
'restriction':"value > 1"
},
...
In this example, the passed int parameter gets evaluated and has to be be greater than one.
The word value is the placeholder for your function parameter.
To give you another example, you can use "value in ['yes', 'no', 'maybe']" to evaluate if the passed string parameter is one of the elements in the list.
With this technique you are able to do some pretty awsome stuff!
If you want further examples, please refere to the examples? section.
INSTALL? Back to top
There are two ways to install tcheasy.
The easy way is to use pip:
$ pip install tcheasy
The other option is to git clone the project and then run:
$ pip install 'path-to-your-clone'
If you want to tinker with your code, run the pip install with -e.
WHERE IS SORPA? Back to top
Mr. Tcheasy comes packed with his friend Sorpa!
sorpa() is a python function which shows you the passed parameters, names, declartions and hints of your targeted python function at runtime.
The import is as easy as the import for tcheasy. Just:
from tcheasy import sorpa
This function takes as input the function (func) you want to analyse and the locals (loc).
As soon as you passed those two arguments, you get a handy dict which sorted the passed parameters, your declared parameter (during function definition) & python hints.
For example, lets consider the following test function:
# we define our test function (called 'test_function') with the parameters a, b & c
# also we add some type hinting
def test_function(a:int, b:str, c:float = .1) -> dict:
"""Our test function. Proper docstring skipped """
# get our local variables
loc = locals()
# lets consider we already imported 'sorpa'
# we set decorated to 'False' to tell the algorithmn
# that we are not within a decorator scope.
sortedParameters = sorpa(
func = test_function,
loc = loc,
decorated = False
)
return sortedParameters
Now we can call the function with some arguments (e.g. test_function(5, b="some-string")) and get as a return the following:
>> {
'positional': {'a': 5, 'b': 'some-string', 'c': 0.1},
'args':[],
'kwargs':{},
'hinting':{'a': <class 'int'>, 'b': <class 'str'>, 'c': <class 'float'>},
'declared': ['a', 'b', 'c'],
'self':{'available':False, 'value':None}
}
EXAMPLES? Back to top
To get some examples, please check out the examples directory (on github).
There you will find examples for Mr. Tcheasy's & and his friend Sorpa's usecases.
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 tcheasy-1.1.0.tar.gz.
File metadata
- Download URL: tcheasy-1.1.0.tar.gz
- Upload date:
- Size: 16.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5c05c0f9168951b21f66fef60c1413906ade54848aa26808f29af6bd692f1030
|
|
| MD5 |
93c22fcf43157e3263faad816050762b
|
|
| BLAKE2b-256 |
fac3acd138cbf97e51dc70c553a93c586da5076fe4c1882b6c892d16b108c781
|
File details
Details for the file tcheasy-1.1.0-py3-none-any.whl.
File metadata
- Download URL: tcheasy-1.1.0-py3-none-any.whl
- Upload date:
- Size: 14.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f0e1e59dff62c29ecd3e163f64ed2e3432fda79dbf749ea7286fe6b083c5c99c
|
|
| MD5 |
a890738cf2c20b97617933f0c58053ab
|
|
| BLAKE2b-256 |
4a14658d957c75dfaa8df20d939daed9a73591177c36c43439352286e3090ddb
|