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?
{}
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!
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