Skip to content

Instantly share code, notes, and snippets.

@courtc
Created March 10, 2017 16:02
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 courtc/17b2416248b8bfeab7932fc2c17e5130 to your computer and use it in GitHub Desktop.
Save courtc/17b2416248b8bfeab7932fc2c17e5130 to your computer and use it in GitHub Desktop.
Class static method variable decorator
from functools import wraps
def class_static_vars(**kwargs):
def decorator(fn):
@wraps(fn)
def wrap(*args):
if not wrap._done:
method = getattr(args[0], fn.__name__)
for k in kwargs:
setattr(method.__func__, k, kwargs[k])
wrap._done = True
return fn(*args)
wrap._done = False
return wrap
return decorator
# # Example use:
#
# class foo:
# @class_static_vars(mydata=42)
# def dostuff(self, var):
# return var + self.dostuff.mydata
#
# print foo().dostuff.mydata # << error: dostuff needs to be called on a object first
# f = foo()
# f.dostuff(12)
# print f.dostuff.mydata # valid
# print foo().dostuff.mydata # valid: data is assigned to class func, not bound method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment