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 | |
|---|---|
1 2 3 4 5 | |
The following two are equivalent:
| Python Console Session | |
|---|---|
1 2 3 | |
| Python Console Session | |
|---|---|
1 2 3 | |
Source code in danling/utils/decorators.py
| Python | |
|---|---|
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
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
| Python | |
|---|---|
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | |
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
|
|
object
|
Additional positional arguments passed to |
()
|
|
object
|
Additional keyword arguments passed to |
{}
|
Examples:
| Python Console Session | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
Source code in danling/utils/decorators.py
| Python | |
|---|---|
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
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
| Python | |
|---|---|
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | |