Strange behaviour of CO_NEWLOCALS and function
Boris Boutillier
boris at cantal.lip6.fr
Wed Apr 10 11:29:41 EDT 2002
Here is a little example, where I create a new codeobject from one of a
function by just removing the CO_NEWLOCALS flags :
>>> import new
>>> CO_NEWLOCALS = 0x2
>>>
>>> def g():
... print 'locals in g :',locals()
... if x: t=2
...
>>> gcode = g.func_code
>>>
>>> newcode = new.code(
... gcode.co_argcount
... , gcode.co_nlocals
... , gcode.co_stacksize
... , gcode.co_flags & ~CO_NEWLOCALS
... , gcode.co_code
... , gcode.co_consts
... , gcode.co_names
... , gcode.co_varnames
... , gcode.co_filename
... , gcode.co_name
... , gcode.co_firstlineno
... , gcode.co_lnotab
... )
>>>
>>> l = {'test':3,'toto':4,'t':2}
>>> g = {'x':1}
>>>
>>> print l
{'test': 3, 'toto': 4, 't': 2}
>>> eval(newcode,g,l)
locals in g : {'test': 3, 'toto': 4} # There is no more 't' here !!!
>>> print l
{'test': 3, 'toto': 4} # 't' has been deleted from
dictionnary
The strange thing is that no new dictionnary is created as expected, but
local variable have been deleted from this dictionnary, why is this ? Is
there some way to modify my code to avoid this deletion ?
Boris
executio
More information about the Python-list
mailing list