harukaeru
harukaeru

Reputation: 713

What's the difference between locals() and globals()

I don't understand what's wrong with in this code.

Please let me know how I write to solve this problem.

I'd thought that this might had been good, but it caused the error.

>>> def L():
...     for i in range(3):
...             locals()["str" + str(i)] = 1
...     print str0
... 
>>> L()

If I execute it, the following error happened.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in a
NameError: global name 'str0' is not defined

However, if I use globals(), the error didn't happen(like the following)

>>> def G():
...     for i in range(3):
...             globals()["str" + str(i)] = 1
...     print str0
... 
>>> G()
1

But!!! If I don't use for statement, I can write like this and works well.

>>> def LL():
...     locals()["str" + str(0)] = 1
...     print str0
... 
>>> LL()
1

I want to get the result by using variables set in the method after the above code was executed.

>>> str0
1
>>> str1
1
>>> str2
1

Upvotes: 1

Views: 85

Answers (1)

kazagistar
kazagistar

Reputation: 1597

From the documentation of locals()

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.

Upvotes: 4

Related Questions