[Python-Dev] locals(), closures, and IronPython...

Andrew Dalke dalke at dalkescientific.com
Tue Mar 6 09:41:53 CET 2007

On 3/5/07, Guido van Rossum <guido at python.org> wrote:
> I don't know too many good use cases for
> locals() apart from "learning about the implementation" I think this
> might be okay.

Since I'm watching this list for any discussion on the traceback
threads, I figured I would point out the most common use I know
for locals() is in string interpolation when there are many local
variables, eg:

   a = "spam"
   b = "egg"
   y = "foo"
   z = "bar"

  print fmtstr % locals()

The next most is to deal with a large number of input parameters, as
this from decimal.py:

    def __init__(self, prec=None, rounding=None,
                 traps=None, flags=None,
                 Emin=None, Emax=None,
                 capitals=None, _clamp=0,
        for name, val in locals().items():
            if val is None:
                setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
                setattr(self, name, val)

and this example based on a post of Alex Martelli's:

    def __init__(self, fee, fie, foo, fum):
        del self.self

In both cases they are shortcuts to "reduce boilerplate".

I've more often used the first form in my code.  If an
inner local returned a superset of the items it returns now,
I would not be concerned.

I've rarely used the 2nd form in my code.  The only way
I can see there being a problem is if a function defines
a class, which then uses the locals() trick, because

>>> def blah():
...    a = 6; b = 7
...    class XYZ(object):
...      def __init__(self):
...        c = a
...        print "in the class", locals()
...    print "in the function", locals()
...    XYZ()
>>> blah()
in the function {'a': 6, 'XYZ': <class '__main__.XYZ'>, 'b': 7}
in the class {'a': 6, 'c': 6, 'self': <__main__.XYZ object at 0x72ad0>}

the code in the class's initializer will have more locals.  I've
never seen code like this (class defined in a function, with __init__
using locals()) and it's not something someone would write
thinking it was a standard way of doing things.

In both cases I'm not that bothered if it's implementation specific.
Using locals has the feel of being too much like a trick to get
around having to type so much.  That's what editor macros are for :)

        dalke at dalkescientific.com

More information about the Python-Dev mailing list