trying to modify locals() dictionary

T

TP

Hi everybody,

I try to modify locals() as an exercise.
According to the context (function or __main__), it works differently (see
below). Why? Thanks

Julien

########################################
def try_to_modify_locals( locals_ ):

locals_[ "a" ] = 2
print "locals_[ 'a' ]=", locals_[ "a" ]
return locals_

def test_modify_locals():

a = 3
l = try_to_modify_locals( locals() )
print l is locals()
print a

# Below, a remains equal to 3
print "test from test_modify_locals()"
test_modify_locals()

# But here, it works: a is modified
print "test from __main__"
a = 3
l = try_to_modify_locals( locals() )
print l is locals()
print a
########################################
--
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
 
A

Albert Hopkins

Hi everybody,

I try to modify locals() as an exercise.
According to the context (function or __main__), it works differently (see
below). Why? Thanks

Julien

Per the locals() documentation @
http://docs.python.org/library/functions.html

Warning

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top