Created
March 10, 2017 16:02
-
-
Save courtc/17b2416248b8bfeab7932fc2c17e5130 to your computer and use it in GitHub Desktop.
Class static method variable decorator
This file contains 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
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