Symbols as parameters?
Alf P. Steinbach
alfps at start.no
Fri Jan 22 03:29:18 EST 2010
* Martin Drautzburg:
> 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
Uhm, interesting technique, technically.
But have you tested this within a function or class, which is what the use of
"locals" implies?
The reason that I ask is that in the documentation of locals() it says this:
Note
The contents of this dictionary should not be modified; changes may not
affect the values of local variables used by the interpreter.
(There's no such note for 'globals').
I have to admit that I was afraid to post this question since my experience in
[comp.lang.python] is that when some technical error is pointed out by me, then
most often the person starts a personal attack and credibility attack, injecting
all kinds of noise -- actually that happened yet again as I was writing this
response to you! But, I figure one shouldn't give up one humanity just because
of one group where that happens regularly. I'm sort of counting on you to prove
that there are, counting myself and one other, and perhaps now you, at least
three persons here who are happy for technical corrections from me.
Or, perhaps there's some aspect of locals(), e.g. in the context of decorators,
that I don't know about and can now learn. :-)
Cheers & hth.,
- Alf
More information about the Python-list
mailing list