Reputation: 450
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) ?
Upvotes: 5
Views: 324
Reputation: 4181
Provide an identity decorator in case of bar
unavailability:
try:
import bar
except ImportError:
class bar:
SomeProvidedDecorator = lambda f: f
Upvotes: 6