Skip to content

Instantly share code, notes, and snippets.

@danizen
Last active February 14, 2019 20:44
Show Gist options
  • Save danizen/73b45154b42a40fe4327aba65b219a4a to your computer and use it in GitHub Desktop.
Save danizen/73b45154b42a40fe4327aba65b219a4a to your computer and use it in GitHub Desktop.
Things declared at the class level are "in-scope" within a Python class
def a_decorator_that_takes_arguments(fubar):
def inner_decorator(func):
nonlocal fubar
func.thing = fubar
return func
return inner_decorator
class ThingUsingDecorator(object):
# This object is in scope for the rest of the class declaration
CLASS_GLOBAL = 'xyz'
# So, you can use it when calling the decorator
@a_decorator_that_takes_arguments(CLASS_GLOBAL)
def nonsense_method(self):
return 'abc'
# Example of use
example_thing = ThingUsingDecorator()
print(example_thing.nonsense_method())
print(example_thing.nonsense_method.thing)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment