Last active
August 1, 2019 23:46
-
-
Save victor-torres/50847f27b11283d3ba063c52a1c90468 to your computer and use it in GitHub Desktop.
How to avoid decorating a function with the same decorator again in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def dec(func): | |
_decorators = getattr(func, '_decorators', []) | |
if dec in _decorators: | |
print('Ignoring...') | |
return func | |
_decorators.append(dec) | |
def inner(*args, **kwargs): | |
print('Calling...') | |
return func(*args, **kwargs) | |
setattr(inner, '_decorators', _decorators) | |
return inner | |
@dec | |
@dec | |
def foo(): | |
print('Foo') | |
@dec | |
@dec | |
@dec | |
def bar(): | |
print('Bar') | |
foo() # Ignores once | |
bar() # Ignores twice |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment