Uniforming decorator for functions and classes to retrieve varname
pwwang opened this issue · 0 comments
pwwang commented
Now we are able to do this with class:
from varname import inject_varname
@inject_varname
class Dict(dict):
pass
a = Dict(a=1)
b = Dict(b=2)
a.__varname__ == 'a'
b.__varname__ == 'b'
a.update(b)
a == {'a':1, 'b':2}
Try to extend it to functions:
@inject_varname
def func():
return __varname__
f = func() # f == 'f'
How it works:
def inject_varname(func):
def wrapper():
# get by varname.varname, also inherit the arguments from it for the decorator.
func.__globals__['__varname__'] = var_name # get by varname.varname
try:
return func()
finally:
del func.__globals__['__varname__']
return wrapper
Also considering rename inject_varname
into register
.