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 you guys first.
I realize there’s various other ways to create static variables in Python, but I find those ways ugly. I’d really like to use the below syntax, if possible.
@static(x=0)
def f():
x += 1
print x
f() #prints 1
f() #prints 2
I don’t care if the implementation of static is long or hackity, as long as it works like above.
I created this version, but it only allows a <function>.<varname> syntax, which gets cumbersome pretty quickly with longer function and variable names.
def static(**assignments):
def decorate(func):
for var, val in assignments.items():
setattr(func, var, val)
return func
return decorate
Various things I thought of, but couldn’t get to work were:
- Changing f (the decorated function) into a callable class, and somehow storing the static vars in
selftransparently. - Modifying the globals of f() inside the decorator, and somehow inserting ‘global x’ statements into the code for f.
- Changing f into a generator where we bind the variables by hand and then execute f’s code directly.
Here is a decorator that seems to work.
Note that this requires return locals() at the end of the function due to being unable to set locals from the outside (I don’t have much experience programming so if there is a way, I don’t know it).
The output would be:
EDIT:
I found something at http://code.activestate.com/recipes/410698/ and decided to try adding it to this. It works without the return now.
EDIT again: Changed to to make it a few seconds faster.
Edit 3; changed to function instead of class
tested:
output:
Using settrace slows it down quite drastically.