[Python-Dev] Deprecating locals() (was Re: nested scopes and global: some corner cases)

Guido van Rossum guido@digicool.com
Mon, 12 Mar 2001 08:51:22 -0500


> [GvR]
> > Actually, I intend to deprecate locals().  For now, globals() are
> > fine.  I also intend to deprecate vars(), at least in the form that is
> > equivalent to locals().

[Samuele]
> That's fine for me. Will that deprecation be already active with 2.1, e.g
> having locals() and param-less vars() raise a warning.

Hm, I hadn't thought of doing it right now.

> I imagine a (new) function that produce a snap-shot of the values in the
> local,free and cell vars of a scope can do the job required for simple 
> debugging (the copy will not allow to modify back the values), 
> or another approach...

Maybe.  I see two solutions: a function that returns a copy, or a
function that returns a "lazy mapping".  The former could be done as
follows given two scopes:

def namespace():
    d = __builtin__.__dict__.copy()
    d.update(globals())
    d.update(locals())
    return d

The latter like this:

def namespace():
    class C:
        def __init__(self, g, l):
            self.__g = g
            self.__l = l
        def __getitem__(self, key):
            try:
                return self.__l[key]
            except KeyError:
                try:
                    return self.__g[key]
                except KeyError:
                    return __builtin__.__dict__[key]
    return C(globals(), locals())

But of course they would have to work harder to deal with nested
scopes and cells etc.

I'm not sure if we should add this to 2.1 (if only because it's more
work than I'd like to put in this late in the game) and then I'm not
sure if we should deprecate locals() yet.

> In the meantime (if there's a meantime) is ok for jython to behave
> the way I have explained or not? 
> wrt to exec+locals()+global+nested scopes .

Sure.  You may even document it as one of the known differences.

--Guido van Rossum (home page: http://www.python.org/~guido/)