Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a function is decorated with a specific decorator?

I want to check if a Python function is decorated, and store the decorator parameter in the function dict. This is my code:

from functools import wraps

def applies_to(segment="all"):
    def applies(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            func.func_dict["segment"] = segment
            print func.__name__
            print func.func_dict
            return func(*args, **kwargs)
        return wrapper
    return applies

But looks like the dict is lost:

@applies_to(segment="mysegment")
def foo():
    print "Some function"


> foo() # --> Ok, I get the expected result
foo
{'segment': 'mysegment'}

> foo.__dict__ # --> Here I get empty result. Why is the dict empty?
{}
like image 635
Jorge Arévalo Avatar asked Jan 30 '23 20:01

Jorge Arévalo


1 Answers

Ok, thanks to user2357112's clue, I found the answer. Even with an improvement

from functools import wraps

def applies_to(*segments):
    def applies(func):
        func.func_dict["segments"] = list(segments)
        @wraps(func)
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        return wrapper
    return applies

Thanks!

like image 161
Jorge Arévalo Avatar answered Feb 02 '23 10:02

Jorge Arévalo