python gripes survey
sross at connectmail.carleton.ca
Wed Aug 27 21:30:23 CEST 2003
"Gonçalo Rodrigues" <op73418 at mail.telepac.pt> wrote in message
news:15dpkvsfatkrlode3rc9h1trihsb3ppcj3 at 4ax.com...
> Related with this is the global declaration -- the only
> declaration in Python! There should be another way to handle this:
> something like scopes becoming objects where the names bound in it are
> it's attributes and then you would have two functions global() and
> enclosing() returning the global and the enclosing scope. Or something
> to this effect :-)
This is probably not what you want, and it's probably worse than just using
a global declaration, but it *is* "another way to handle this":
>>> # put this at the top of your module,
>>> # to grab hold of this module's namespace
>>> import __main__ as main
>>> g = "global variable"
>>> def f():
... main.g = "re-bound global"
If you want a global() function that returns the namespace, you can do this:
# I'll use the name 'main' rather than shadow the global keyword
from your_utils import main
foo = "foo"
I have no idea what issues this raises, but that is not my concern here -
I'm just seeing whether there is "another way to handle this". It looks like
there is. Usual disclaimers apply: "Don't do that", "Use at your own risk",
I can't help you with "names bound in nested scopes are read-only, not
rebindable". I tried to implement your enclosing() idea. I made a
'namespace' class to use as follows:
x = 1
# context is the number of frames to go back
outer = namespace(context=1)
# outer keeps a reference to foo's frame
outer.x = 2
# so, I tried to re-bind the x in foo using something like
# self.frame.f_locals['x'] = 2, but f_locals is not writable!
# I made several attempts to circumvent this, but no success.
"just seeing if it can be done-ly yours"
More information about the Python-list