Lets say I have the following code:
try:
import bar
except ImportError:
bar = None
@bar.SomeProvidedDecorator
def foo():
pass
where bar is an optional dependency. The code above will fail, if bar isn't imported. Is there a recommended way of dealing with this problem?
I came up with:
try:
import bar
except ImportError:
bar = None
def foo():
pass
if bar is not None:
foo = bar.SomeProvidedDecorator(foo)
but I'm wondering if there are better ways of handling this (i.e. is there a way to keep the decorator syntax) ?
The path operation decorator receives an optional argument dependencies. These dependencies will be executed/solved the same way normal dependencies. But their value (if they return any) won't be passed to your path operation function.
This decorator only gives Angular information about the dependencies this service wants, but if it doesn’t have any, then the decorator is optional! So the second option is correct and the first one false. The third option is false because if our service has dependencies, that means the @Injectable operator is needed!
This means that if either Decorator or the wrapped service have other dependencies that are registered later then they won’t be available. This is possibly not the worst problem in the world but it could lead to a nasty category of bug that would be very difficult to track down. Can we do better?
In Decorators, functions are taken as the argument into another function and then called inside the wrapper function. In the above code, gfg_decorator is a callable function, will add some code on the top of some another callable function, hello_decorator function and return the wrapper function. print("This is inside the function !!")
Provide an identity decorator in case of bar
unavailability:
try:
import bar
except ImportError:
class bar:
SomeProvidedDecorator = lambda f: f
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With