Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mmaelicke/dtype-decorate
Mini-library for data-type check and conversion decorators.
https://github.com/mmaelicke/dtype-decorate
Last synced: about 2 months ago
JSON representation
Mini-library for data-type check and conversion decorators.
- Host: GitHub
- URL: https://github.com/mmaelicke/dtype-decorate
- Owner: mmaelicke
- License: mit
- Created: 2017-07-25T09:02:41.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2017-07-26T08:49:09.000Z (over 7 years ago)
- Last Synced: 2024-10-16T04:41:04.876Z (3 months ago)
- Language: Python
- Size: 8.79 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.rst
- License: LICENSE
Awesome Lists containing this project
README
DType-Decorate
==============The DType-Decorate module defines two different decorators at the current state. These decorators can be used to
constrain the attributes of the decorated function to specific data types. This can help to keep functions clean
especially when they are written for a specific context. This is usually the case for scientific applications,
where functionality is often more important than clean code.The basic structure of this module was heavily inspired / extended on the basis of:
https://stackoverflow.com/questions/15299878/how-to-use-python-decorators-to-check-function-argumentsInstallation
~~~~~~~~~~~~You can either use `pip` to install the version from PyPI or git to install the probably more recent version from
github... code-block:: bash
git clone http://github.com/mmaelicke/dtype-decorate.git
cd dtype-decorate
pip install -r requirements.txt
python setup.py install.. code-block:: bash
pip install dtype-decorate
Usage
~~~~~There are two decorators so far: `accept` and `enforce`. `accept` will restrict the attribute data types to the
the defined ones, while `enforce` will try to convert the given attribute to a desired data type.
Both can also be used together, where `accept` does only make sense to be used after `enforce`.Define a function that does only accept an `int` and a `float`.
.. code-block:: python
import ddec
@ddec.accept(a=int, b=float)
def f(a, b):
passYou can also specify more than one data type allowed. Any attribute not given in the decorator will just be
ignored... code-block:: python
@ddec.accept(a=(int, float))
def f(a, be_any_type)
passf(5, 'mystr') # will run fine
f('mystr', 5) # will raise a TypeErrorThe `accept` decorator can also handle None type and callables like functions or lambda. These have to be specified
as a string... code-block:: python
@ddec.accept(a='None', b=('None', 'callable'))
def f(a, b):
passf(None, None) # will run fine
f(None, lambda x: x) # will run fine
f(5, None) # will raise a TypeError