iterating initalizations
Steve Holden
steve at holdenweb.com
Tue Dec 23 11:10:52 EST 2008
D'Arcy J.M. Cain wrote:
> On Tue, 23 Dec 2008 10:20:59 -0500
> Steve Holden <steve at holdenweb.com> wrote:
>> D'Arcy J.M. Cain wrote:
>>> Well, if all you want is a loop:
>>>
>>> for v in vars:
>>> locals()[v] = []
>>>
>> Note that this isn't guaranteed to work. While locals() will return a
>> dict containing the names and values from the local namespace, you won't
>> affect the local namespace by assigning values to the appropriate keys:
>>
>>>>> def f():
>> ... a = "hello"
>> ... locals()["a"] = "goodbye"
>> ... print a
>
> This was my test:
>
>>>> locals()['x'] = "hello"
>>>> x
> 'hello'
>>>> locals()['x'] = "goodbye"
>>>> x
> 'goodbye'
>
> Just didn't want people to think that I post without testing.
>
> In any case, even if that worked as expected I am pretty sure that it
> is the wrong solution but without knowing more about what the OP is
> doing it is impossible to know what the right answer is.
>
The thing you overlooked was that the locals of a function are special.
The locals of a module are the globals!
>>> def lisg():
... return locals() is globals()
...
>>> locals() is globals()
True
>>> lisg()
False
>>>
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list