Skip to content

Instantly share code, notes, and snippets.

@victor-torres
Last active August 1, 2019 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victor-torres/50847f27b11283d3ba063c52a1c90468 to your computer and use it in GitHub Desktop.
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
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