Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using decorators of optional dependency

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) ?

like image 952
Julian S. Avatar asked Aug 11 '21 12:08

Julian S.


People also ask

What are optional dependencies in the path operation decorator?

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.

Does this decorator only give angular information about dependencies this service wants?

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!

What happens if decorator or the wrapped service have other dependencies?

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?

How to call a function from another function in decorator?

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 !!")


1 Answers

Provide an identity decorator in case of bar unavailability:

try:
    import bar
except ImportError:
    class bar:
        SomeProvidedDecorator = lambda f: f
like image 154
Roman Pavelka Avatar answered Oct 17 '22 02:10

Roman Pavelka