Common interface for archive manipulation
Project description
decoutils: Utilities for writing decorators
Rationale
Python decorators are very useful. However, writing decorators with arguments is not straightforward. Take the following function as an example:
register_plugin(plugin, arg1=1):
print('registering ', plugin.__name__, ' with arg1=', arg1)
This function registers a input function somewhere in the system. If this function could work as a decorator, that will be convinient. In order to make it a decorator, we just need it to return the input plugin trivially:
register_plugin(plugin, arg1=1):
print('registering ', plugin.__name__, ' with arg1=', arg1)
return plugin
@register_plugin
def plugin1(): pass
It is pretty easy so far. What if we want register_plugin works as a decorator with arguments? That's to say, we want to use it as:
@register_plugin(arg1=2)
def plugin2(): pass
In order to accomplish this goal, we need to wrap the function register_plugin so that it return a decorated plugin if the first input is a callable object, otherwise return a decorator with arguments. The decoutils.decorator_with_arguments is intend to abstract that wrapping, so that we can reuse it.
Installation
Install from PyPI
pip install compfile
Install from Anaconda
conda install -c liyugong compfile
Simple example
Basically, decorator_with_arguments enables a ordinary decorator function to be a decorator with arguments.
@decorator_with_arguments
def register_plugin(plugin, arg1=1):
print('registering ', plugin.__name__, ' with arg1=', arg1)
return plugin
@register_plugin(arg1=10)
def plugin1(): pass
Moreover, decorator_with_arguments itself is also a decorator with arguments: one argument return_original which can be used to convert a non-decorator function to be a decorator
@decorator_with_arguments
def register_plugin(plugin, arg1=1):
print('registering ', plugin.__name__, ' with arg1=', arg1)
# Note here the function does not return the plugin, so it cannot work as a decorator originally
@register_plugin(arg1=10)
def plugin1(): pass
return_original control whether the resultant decorator return the original plugin, or the result of function register_plugin.
License
The compfile package is released under the MIT License
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
Hashes for decoutils-0.0.1-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | b4aa5798b863c1056b002d8f9599e51a0dd93cfe4c39ccc4dae98f25116817f3 |
|
MD5 | dc8fdfbcb030fd42d7834c6eeb73e7f2 |
|
BLAKE2b-256 | 863b506ee8e8bef87e2c80d91879952c7db84abe12647cf8cec3dc8221cfe049 |