How safe is modifying locals()?
tjreedy at udel.edu
Fri Jul 25 19:03:13 CEST 2003
"Paul Paterson" <paulpaterson at users.sourceforge.net> wrote in message
news:BDcUa.100193$XV.6037947 at twister.austin.rr.com...
> I am trying to find a way to mimic by-reference argument passing for
> immutables in Python. I need to do this because I am writing an
> automated VB to Python converter.
> Here's an example of the VB code:
> Sub Change(ByVal x, ByRef y)
> x = x+1
> y = y+1
> End Sub
> x = 0: y = 0
> Change x, y
> ' Now x should be 0 and y should be 1
> One approach that has been suggested is to use locals() and indirect
> references to the immutable via the resulting dictionary,
> def change(x, y, refs):
> x = x + 1
> refs[y] = refs[y] + 1
> x = 0; y = 0;
> change(x, 'y', locals())
> The Python documentation gives a warning that modifying the contents
> locals() may not affect local values. Despite the warning, the code
> seems to work as desired, at least on Python 2.2.
At module scope, locals() == globals(). Within a function, locals()
currently is a *copy* of the function's local namespace. So above
only works because you made the call from the global (module) context
and would not if you tested by making call from within a function.
Terry J. Reedy
More information about the Python-list