python gripes survey

Sean Ross sross at
Wed Aug 27 21:30:23 CEST 2003

"Gonçalo Rodrigues" <op73418 at> wrote in message
news:15dpkvsfatkrlode3rc9h1trihsb3ppcj3 at
> 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"
>>> f()
>>> 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
def main():
    import __main__
    return __main__

from your_utils import main
foo = "foo"
def bar():
    print main().foo

# output

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",
"Yada, Yada"

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:

def foo():
    x = 1
    def bar():
        # 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.
    print x


# output

Oh well...

"just seeing if it can be done-ly yours"

More information about the Python-list mailing list