Why use "locals()"

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Sep 14 06:11:44 CEST 2009

On Sun, 13 Sep 2009 20:26:06 -0700, Sean DiZazzo wrote:

> On Sep 13, 8:18 pm, Steven D'Aprano
> <ste... at REMOVE.THIS.cybersource.com.au> wrote:
>> On Sun, 13 Sep 2009 20:06:51 -0700, Sean DiZazzo wrote:
>> > I have never used a call to "locals()" in my code.  Can you show me a
>> > use case where it is valuable and Pythonic?
>> grep is your friend:
>> $ grep "locals()" /usr/lib/python2.5/*.py
>> /usr/lib/python2.5/decimal.py:        for name, val in
>> locals().items(): /usr/lib/python2.5/doctest.py:        return
>> __import__(module, globals(), locals(), ["*"])
>> /usr/lib/python2.5/profile.py:        p.runctx('f(m)', globals(),
>> locals()) /usr/lib/python2.5/pydoc.py:            docloc = '<br><a
>> href="%(docloc)s">Module Docs</a>' % locals()
>> /usr/lib/python2.5/smtpd.py:        mod =
>> __import__(classname[:lastdot], globals(), locals(), [""])
>> --
>> Steven
> That is not a use case. I still don't understand!

Look at the source code to find out what they're doing with the 
information they extract from locals(), and why.

For instance, profile should be obvious -- debuggers and profilers often 
need to see the values of local names.

pydoc is using the fairly common idiom of injecting the values of 
variables into a string. Personally, I don't see why it uses this idiom:

    docloc = 'something'
    docloc = '%(docloc)s' % locals()

instead of this:

    docloc = 'something'
    docloc = '%s' % docloc

but for more complicated cases, the first idiom is much simpler.

decimal seems to be using locals() to avoid this anti-pattern:

def __init__(self, a, b, c, d, e, f, g, h):
    self.a = a
    self.b = b
    self.c = c
    self.d = d
    # blah blah blah
    self.h = h

and replacing it with:

def __init__(self, a, b, c, d, e, f, g, h):
    for name, val in locals().items():
        setattr(self, name, val)
    del self.self

Another use-case: if you have a tool that documents Python code 
automatically, it needs a way to automatically view the values of local 

> PS.  I know how to use grep.

I'm sure you do. But you didn't think of using grep, which is why I made 
the suggestion that grepping the standard library is a good tool to use 
to search for Pythonic examples of code.

It's not foolproof, e.g. the unittest module is more Java-onic than 
Pythonic, but it's a good start.


More information about the Python-list mailing list