Decorators¶
danling.utils.decorators
¶
flexible_decorator
¶
Meta decorator to allow bracket-less decorator when no arguments are passed.
Examples:
For decorator defined as follows:
| Python Console Session | |
|---|---|
The following two are equivalent:
Source code in danling/utils/decorators.py
print_exc
¶
Print exception raised by func with args and kwargs to stderr.
This function serves as the default callback for catch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int
|
What level of traceback to print. 0-: No traceback. 0-10: Full information of arguments and key word arguments. 10-20: Stack trace to function calls. 40+: Function name and error messages. |
40
|
Source code in danling/utils/decorators.py
catch
¶
catch(error: Exceptions = Exception, exclude: Exceptions | None = None, callback: Callable = print_exc, *callback_args, **callback_kwargs)
Decorator to catch error except for exclude.
Detailed traceback will be printed to stderr.
catch is extremely useful for unfatal errors.
For example, Runner saves checkpoint regularly, however, this might break running if the space is full.
Decorating save method with catch will allow you to catch these errors and continue your running.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Exceptions
|
Exceptions to be caught. |
Exception
|
|
Exceptions | None
|
Exceptions to be excluded. |
None
|
|
Callable
|
Callback to be called when an error occurs.
The first four arguments to |
print_exc
|
|
Arguments to be passed to |
()
|
|
|
Keyword arguments to be passed to |
{}
|
Examples:
Source code in danling/utils/decorators.py
method_cache
¶
Decorator to cache the result of an instance method.
functools.lru_cache uses a strong reference to the instance,
which will make the instance immortal and break the garbage collection.
method_cache uses a weak reference to the instance to resolve this issue.