Decorator¶
danling.utils.decorators
¶
flexible_decorator
¶
Meta decorator to allow bracket-less decorator when no arguments are passed.
Examples:
For decorator defined as follows:
>>> @flexible_decorator
... def decorator(*args, **kwargs):
... def wrapper(func, *args, **kwargs):
... pass
... return wrapper
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
¶
Python | |
---|---|
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:
>>> def file_not_found(*args, **kwargs):
... raise FileNotFoundError
>>> func = file_not_found
>>> func()
Traceback (most recent call last):
FileNotFoundError
>>> func = catch(OSError)(file_not_found)
>>> func()
>>> func = catch(IOError)(file_not_found)
>>> func()
>>> func = catch(ZeroDivisionError)(file_not_found)
>>> func()
Traceback (most recent call last):
FileNotFoundError
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.
See Also
Source code in danling/utils/decorators.py
ensure_dir
¶
Python | |
---|---|
Decorator to ensure a directory property exists.
Note
Please avoid using this with cached_property
.
Examples:
>>> @property
... @ensure_dir
... def dir(self) -> str:
... return os.path.join("path", "to", "dir")