I\'d like to create a decorator like below, but I can\'t seem to think of an implementation that works. I\'m starting to think it\'s not possible, but thought I would ask yo
You could do something like that (but I haven't tested this extensively; used CPython 2.6):
import types
def static(**dict):
def doWrap(func):
scope = func.func_globals
scope.update(dict)
return types.FunctionType(func.func_code, scope)
return doWrap
# if foo() prints 43, then it's wrong
x = 42
@static(x = 0)
def foo():
global x
x += 1
print(x)
foo() # => 1
foo() # => 2
It requires declaring those variables as global and shadows top-level global variables, but otherwise should work. Not sure about performance, though.