4

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?
{}
martineau
  • 119,623
  • 25
  • 170
  • 301
Jorge Arévalo
  • 2,858
  • 5
  • 36
  • 44

1 Answers1

8

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!

Jorge Arévalo
  • 2,858
  • 5
  • 36
  • 44
  • In Python 3 the `func_dict` attribute has been renamed to `__dict__`. You also need to change the `*segments` to `**segements` in order to use `@applies_to(segment="mysegment")`. – martineau Mar 11 '22 at 15:01