binding a reference to a variable

Andrew Koenig ark at research.att.com
Tue Apr 9 16:56:52 EDT 2002


Mark> [Andrew Koenig]

>> What I would really like is to be able to define a function called,
>> say, `set' such that set(x, 42) has the same effect as `x = 42'.

Mark> What about this?

Mark>   def set(name, value):
Mark>     globals()[name] = value

Mark>   set("x", 5)

Mark>   print x

Mark> The only difference is that you pass set a string representation of the
Mark> variable you want to set.  Close, but no cigar?

Close, but no cigar.  A few problems:

       It's restricted to global variables.

       It uses the relationship between variables and their names
       at run time, and I would prefer the mapping to be done at
       compile time.

Mark> There's also this recipe:

Mark>   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/80373

Same problem

Mark> I'm curious why you need this?

I want to be able to stuff an object into a larger data
structure and have that object reach out into a variable and leave a
trail of breadcrumbs.




      






More information about the Python-list mailing list