NameError: how to get the name?

Chris Rebert clp2 at rebertia.com
Sat Apr 24 19:27:12 EDT 2010


On Sat, Apr 24, 2010 at 4:17 PM, Yingjie Lan <lanyjie at yahoo.com> wrote:
> --- On Sat, 4/24/10, Gary Herron <gherron at islandtraining.com> wrote:
>> From: Gary Herron <gherron at islandtraining.com>
>> Date: Saturday, April 24, 2010, 8:03 PM
>> Yingjie Lan wrote:
>> > --- On Sat, 4/24/10, Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au>
>> wrote:
>> >> From: Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au>
>> >> Subject: Re: NameError: how to get the name?
>> >> To: python-list at python.org
>> >> Date: Saturday, April 24, 2010, 4:07 PM
>> >> On Sat, 24 Apr 2010 04:19:43 -0700,
>> >> Yingjie Lan wrote:
>> >>
>> >>
>> >>> I wanted to do something like this:
>> >>>
>> >>> while True:
>> >>>   try:
>> >>>     def fun(a, b=b, c=c):
>> pass
>> >>>   except NameError as ne:
>> >>>     name =
>> get_the_var_name(ne)
>> >>>     locals()[name] = ''
>> >>>   else: break
>> >>>
>> >> This won't work. Writing to locals() does not
>> actually
>> >> change the local variables. Try it inside a
>> function, and you will see it
>> >> doesn't work:
>
> No it DOESN'T work, and both of you are precisely correct.
> Just for playing around, I substituted
> "locals()" by "globals()" and it worked as desired:
<snip>
> Thanks for the information! BTW, why would
> locals() and globals() differ in this respect?

The module-level (i.e. global) namespace is implemented by CPython
using an actual dictionary; globals() returns a proxy to that
dictionary and lets you manipulate it.
In contrast, as an optimization, CPython implements local variables in
functions using predetermined offsets into an array of predetermined
length; the dictionary returned by locals() is dynamically constructed
on-demand and does not affect the actual array used for the local
variables (I suppose it could have been made to do so, but there's
probably a complexity or optimization reason for why not).

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list