How safe is modifying locals()?
Paul Paterson
paulpaterson at users.sourceforge.net
Fri Jul 25 12:10:09 EDT 2003
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 of
locals() may not affect local values. Despite the warning, the code
seems to work as desired, at least on Python 2.2.
Does anyone know how safe this approach is, particularly in a
multithreaded environment? Will this work on Jython?
Does anyone have any alternative strategies for trying to achieve the
objective? A "Pythonic" approach such as,
def change(x, y):
x = x + 1
y = y + 1
return y
x = 0; y = 0
y = change(x, y)
Works in a single threaded environment but, because the value of 'y'
changes at the wrong time, with multiple threads there is a possibility
that two users of 'y' could dissagree on its value.
Paul
Paul Paterson
(paulpaterson at users.sourceforge.net)
vb2py :: A Visual Basic to Python Conversion Toolkit
http://vb2py.sourceforge.net
More information about the Python-list
mailing list