Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deactivate function with decorator

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?

like image 952
Themerius Avatar asked Jul 30 '13 11:07

Themerius


1 Answers

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
like image 68
Martijn Pieters Avatar answered Oct 28 '22 05:10

Martijn Pieters