NameError: how to get the name?

Gary Herron gherron at islandtraining.com
Sat Apr 24 12:03:56 EDT 2010


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:
>>
>>     
>
> I tried this, and it worked:
>
> Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
> [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>   
>>>> while True:
>>>>         
> ...     try: print a
> ...     except: locals()['a']="HERE YOU ARE"
> ...     else: break
> ... 
> HERE YOU ARE
>   

Yes, but as Steven D'Aprano said, this won't work inside a function.  
Try it.

Also if you find an instance where this works, you can't rely on the 
behavior.  If you  RTM, you'll find this:

locals()¶ <http://docs.python.org/library/functions.html#locals>

    Update and return a dictionary representing the current local symbol
    table. Free variables are returned by locals()
    <http://docs.python.org/library/functions.html#locals> when it is
    called in function blocks, but not in class blocks.

    Note: The contents of this dictionary should not be modified;
    changes may not affect the values of local and free variables used
    by the interpreter.

Gary Herron







More information about the Python-list mailing list