Concise idiom to initialize dictionaries
Gert-Jan den Besten
gj.den.besten at hccnet.nl
Tue Nov 9 13:01:19 EST 2004
Frohnhofer, James wrote:
> My initial problem was to initialize a bunch of dictionaries at the start of a
> function.
>
> I did not want to do
> def fn():
> a = {}
> b = {}
> c = {}
> . . .
> z = {}
> simply because it was ugly and wasted screen space.
>
> First I tried:
>
> for x in (a,b,c,d,e,f,g): x = {}
>
> which didn't work (but frankly I didn't really expect it to.)
> Then I tried:
>
> for x in ('a','b','c','d','e','f','g'): locals()[x]={}
>
> which did what I wanted, in the interpreter. When I put it inside a function,
> it doesn't seem to work. If I print locals() from inside the function, I can
> see them, and they appear to be fine, but the first time I try to access one
> of them I get a "NameError: global name 'a' is not defined"
>
> Now obviously I could easily avoid this problem by just initializing each
> dictionary, but is there something wrong about my understanding of locals,
> that my function isn't behaving the way I expect?
Any variable you assign within a function, is local to that function.
You cannot refer to it from the enclosing function or module.
If you use a global declaration in the function, you can alter variables
outside your function. (You can also pass variables using the function
header.) e.g:
x = 42
def a_function():
global x
x = "another value"
print x
a_function()
print x
But i don't think this is good programming practice.
Gert-Jan
More information about the Python-list
mailing list