Puzzle: anonymous tuple unpacking w/o eval

Jeremy Yallop jeremy at jdyallop.freeserve.co.uk
Fri May 16 08:56:05 EDT 2003


Edward K. Ream wrote:
> For a long time I've wondered how to generalize tuple unpacking, such as:
> 
> a,b,c = (val1,val2,val3)
> 
> so that it isn't necessary for code to know the names of vars or ivars.
> 
> Eval can be used sometimes:
> 
> aList = (("a",val1),("b",val2),("c",val3))
> ...
> for name,val in aList:
>   eval("%s=%s" % (name,str(val)))
> 
> This only works for string and numeric values where str(val)==repr(val),
> sort of.
> 
> Anyway, is there any way to get the same effect without using eval?  setattr
> might be useful, and I haven't figured out how.

Are you looking for something like

  __import__(__name__).__dict__.update(dict(tuple))

(or, perhaps,

  globals().update(dict(tuple))

)?

  >>> def update_vars(tup):
  ...     globals().update(dict(tup))
  ...
  >>> update_vars( (('a', 1,), ('b', 'two',)))
  >>> a
  1
  >>> b
  'two'

Jeremy.




More information about the Python-list mailing list