[Tutor] loops to assign variables

Kent Johnson kent37 at tds.net
Sat Jul 22 19:41:17 CEST 2006


Dave Kuhlman wrote:
> On Sat, Jul 22, 2006 at 11:37:38AM -0400, Python wrote:
>   
>>
>> Well the reference documentation says:
>>
>> locals(
>> )
>>         Update and return a dictionary representing the current local
>>         symbol table. Warning: The contents of this dictionary should
>>         not be modified; changes may not affect the values of local
>>         variables used by the interpreter.
>>
>> I believe the compiler thinks it knows of all the local variables, so I
>> think assignment to locals() is likely to lead to grief even it appears
>> to work in simple test cases.
>>
>>     
> But, (and I'm going off-topic here and possibly into the ditch
> along the side of the road) ..., locals() returns a dictionary.
> It's a dictionary like any other dictionary.  And, it is that
> dictionary which Python uses to check for the existence of a
> variable *at runtime*.  Yes. That's right.  Python actually does a
> dictionary look-up for each variable at runtime.  This is *not* a
> flaw; it is part of the object model and execution model of
> Python.  And, that's why compile-time (static) type checking in
> Python is either impossible or would require type inference.
>
> And, also, that's why the following statements all have exactly
> the same effect:
>
>     total = 5
>     locals()['total'] = 5
>     exec('total = 5')

You're not in the mood to believe the docs today, eh? Yes, locals() 
returns a dict and yes, you can modify it. And yes, "changes may not 
affect the values of local variables used by the interpreter." In 
particular modifying locals() inside a function doesn't do what you 
think it will:

In [14]: def badlocals():
   ....:     locals()['total'] = 5
   ....:     print total
   ....:

In [15]: badlocals
Out[15]: <function badlocals at 0x00E4AEB0>

In [16]: badlocals()
---------------------------------------------------------------------------
exceptions.NameError                                 Traceback (most 
recent call last)

F:\Bio\BIOE480\Final project\SequenceAlignment\<ipython console>

F:\Bio\BIOE480\Final project\SequenceAlignment\<ipython console> in 
badlocals()

NameError: global name 'total' is not defined

At global scope, locals() == globals() and modifying it affects the 
global namespace. In function scope, I believe locals() is actually a 
copy of the real namespace.

Kent



More information about the Tutor mailing list