binding a reference to a variable

Mark McEahern marklists at mceahern.com
Tue Apr 9 16:50:10 EDT 2002


[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'.

What about this?

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

  set("x", 5)

  print x

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

There's also this recipe:

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

I'm curious why you need this?

Cheers,

// mark







More information about the Python-list mailing list