Is it possible to "deactivate" a function with a python decorator? Here an example:
cond = False
class C:
if cond:
def x(self): print "hi"
def y(self): print "ho"
Is it possible to rewrite this code with a decorator, like this?:
class C:
@cond
def x(self): print "hi"
def y(self): print "ho"
Background: In our library are some dependencies (like matplotlib) optional, and these are only needed by a few functions (for debug or fronted). This means on some systems matplotlib is installed on other systems not, but on both should run the (core) code. Therefor I'd like to disable some functions if matplotlib is not installed. Is there such elegant way?
You can turn functions into no-ops (that log a warning) with a decorator:
def conditional(cond, warning=None):
def noop_decorator(func):
return func # pass through
def neutered_function(func):
def neutered(*args, **kw):
if warning:
log.warn(warning)
return
return neutered
return noop_decorator if cond else neutered_function
Here conditional
is a decorator factory. It returns one of two decorators depending on the condition.
One decorator simply leaves the function untouched. The other decorator replaces the decorated function altogether, with one that issues a warning instead.
Use:
@conditional('matplotlib' in sys.modules, 'Please install matplotlib')
def foo(self, bar):
pass
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