Symbols as parameters?
Martin Drautzburg
Martin.Drautzburg at web.de
Thu Jan 21 17:57:37 EST 2010
Here is a complete expample using a decorator, still a bit noisy
def move(aDirection):
print "moving " + aDirection
#Here comes the decorator
def scope(aDict):
def save(locals):
"""Set symbols in locals and remember their original state"""
setSymbols={}
unsetSymbols=[]
for i in ("up", "down", "left", "right"):
if locals.has_key(i):
setSymbols[i] = locals[i]
else:
unsetSymbols.append(i)
# define the new symbols
locals[i] = i
return setSymbols, unsetSymbols
def restore (locals, set, unset):
"""restore locals from set and unset"""
for i in set.keys():
locals[i] = set[i]
for i in unset:
del(locals[i])
def callFunc(f):
"""Main decorator"""
set, unset = save(aDict)
f()
restore(aDict, set, unset)
return callFunc
# --------------------------------------
# using it
# --------------------------------------
# a variable defined in the outer scope
up="outerScopeUp"
# magic, magic (still too noisy for my taste)
@scope (locals())
def _():
move(up)
move(down)
move(left)
move(right)
#verify the the outer scope variable hasn't changed
print "in the outer scope up is still:", up
print
print "this should fail:"
down
# --------------------------------------
# Output
# --------------------------------------
moving up
moving down
moving left
moving right
in the outer scope up is still: outerScopeUp
this should fail:
Traceback (most recent call last):
File "<stdin>", line 50, in <module>
NameError: name 'down' is not defined
More information about the Python-list
mailing list