How safe is modifying locals()?
Paul Paterson
paulpaterson at users.sourceforge.net
Fri Jul 25 22:11:05 EDT 2003
Ian Bicking wrote:
> On Fri, 2003-07-25 at 12:28, Paul Paterson wrote:
>
>>Thanks Terry! I adjusted my tests and now see this behaviour exactly.
>>The function itself works but the changes do not propogate out to the
>>calling scope. So this approach of using locals() appears to be dead.
>>
>>Are there any other approaches?
>
>
> Think about what you are trying to do, and try to identify a (mutable)
> object that can encapsulate that. Then pass the object, and modify its
> instance variables, like:
>
> class Point:
> def __init__(self, x, y):
> self.x = x
> self.y = y
>
> def change(p):
> p.y = 10
>
> obj = Point(0, 0)
> change(obj)
> assert obj.y == 10
>
>
> Maybe this mutable object will simply be the main application object,
> and instead of functions you will use methods of that application
> object.
>
> Ian
This is a very interesting (and Pythonic) approach, thanks for
suggesting it! This is certainly what I would try to do if I were
writing the code from scratch. It may be possible to construct a
"namespace" type object which gets passed to the function.
VB does have multiple namespaces so a single App object is probably not
feasible but since my parser knows the App structure it can determine
which namespace a variable will be resolved from anyway and just
translate all attempts to access it to the relevant namespace object lookup.
Paul
More information about the Python-list
mailing list