Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 decorating conditionally?

Is it possible to decorate a function based on a condition?

a'la:

if she.weight() == duck.weight(): 
    @burn
def witch():
    pass

I'm just wondering if logic could be used (when witch is called?) to figure out whether or not to decorate witch with @burn?

If not, is it possible to create a condition within the decorator to the same effect? (witch being called undecorated.)

like image 971
MadSc13ntist Avatar asked Nov 29 '22 19:11

MadSc13ntist


2 Answers

You can create a 'conditionally' decorator:

>>> def conditionally(dec, cond):
    def resdec(f):
        if not cond:
            return f
        return dec(f)
    return resdec

Usage example follows:

>>> def burn(f):
    def blah(*args, **kwargs):
        print 'hah'
        return f(*args, **kwargs)
    return blah

>>> @conditionally(burn, True)
def witch(): pass
>>> witch()
hah

>>> @conditionally(burn, False)
def witch(): pass
>>> witch()
like image 70
Claudiu Avatar answered Dec 01 '22 09:12

Claudiu


It is possible to enable/disable decorators by reassignment.

def unchanged(func):
    "This decorator doesn't add any behavior"
    return func

def disabled(func):
    "This decorator disables the provided function, and does nothing"
    def empty_func(*args,**kargs):
        pass
    return empty_func

# define this as equivalent to unchanged, for nice symmetry with disabled
enabled = unchanged

#
# Sample use
#

GLOBAL_ENABLE_FLAG = True

state = enabled if GLOBAL_ENABLE_FLAG else disabled
@state
def special_function_foo():
    print "function was enabled"
like image 25
MadSc13ntist Avatar answered Dec 01 '22 10:12

MadSc13ntist