When to write a decorator(context manager) vs When to avoid #46
YooSunYoung
started this conversation in
Design Choices
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
When to write a decorator
Decorator is not neat to write and it has bad readability if it's too complicated,
but it helps very much in some cases like below.
So I wrote down in which cases the decorator bypass the disadvantages.
In order to write a decorator easier, there is a wrapper tool module
beamlime.tools.wrappers
.I will use
wraps_better
from the module in the example code below.It updates the
signature
and__doc__
ofwrapper
function fromwrapped
function.You can also just use
functools.wraps
if you don't want thesignature
to be updated.Validation
If you wrap a block of code with
try-except
for specific error,or you want to validate anything at the beginning or at the end of the function,
it might be easier to write a decorator to do that.
Then you can write a decorator like,
It may look like you just extended the code, but then the actual function we wanted write will look like this:
And if there are multiple functions that need the same validation, it'll reduce a lot of lines of code.
A group of calls wraps a block of code and they MUST be called in order
Any group of code that must be sctrictly called in order is a good candidate to be a decorator or a context manager.
For example, once you lock a thread, you must release the thread at some point.
In this case above, since the thread lock and release is wrapping the try-exception,
so it is a good candidate to be a context manager.
It can be written like below.
Then you can use the context manager like below.
Context manager is much easier to write and read compared to decorator.
If the same context manager was written in a decorator way, it will look like below.
But when you need to see the arguments to the function call, or use the output of the function call you want to wrap, context manager might not be enough.
When to avoid decorator
We don't need decorators in general but we should avoid to write one especially if,
Beta Was this translation helpful? Give feedback.
All reactions