Looking for the best way to translate an idiom

James Stroud jstroud at mbi.ucla.edu
Mon Dec 15 01:25:02 CET 2008


James Stroud wrote:
> py> class mytuple(tuple):
>   def magic(self, astr):
>     names = astr.split()
>     for name, val in zip(names, self):
>       globals()[name] = val
> ...
> py> t = mytuple((1,2,3))
> py> t.magic('a b')
> py> a
> 1
> py> b
> 2
> 
> James


In case its not obvious:

def f():
   return mytuple((1,2,3))

f().magic('a b')

You can parameterize lobbing off values, or use more magic:

py> class mytuple(tuple):
...   def magic(self, astr):
...     names = astr.split()
...     for name, val in zip(names, self):
...       globals()[name] = val
...   def __add__(self, other):
...     if isinstance(other, tuple):
...       return mytuple(tuple.__add__(self, other))
...     else:
...       return mytuple(self[other:])
...
py> t = mytuple((1,2,3))
py> t + 1
(2, 3)
py> def f():
   return mytuple((1,2,3))
...
py> (f() + 1).magic('a b')
py> a
2
py> b
3

It's not as bad as a lot of the cynics are about to tell you it is. If 
it has any badness at all, it's because of the need (according to what I 
infer from your specification) to use the global namespace. If you want 
to modify a "more local" namespace, you can use some stack frame 
inspection to do some real magic:

py> import inspect
py> class mytuple(tuple):
   def magic(self, astr):
     names = astr.split()
     for name, val in zip(names, self):
       inspect.stack()[1][0].f_locals[name] = val
   def __add__(self, other):
     if isinstance(other, tuple):
       return mytuple(tuple.__add__(self, other))
     else:
       return mytuple(self[other:])
...
py> def f():
   return mytuple((6,7,8))
...
py> (f() + 1).magic('a b')
py> a
7
py> b
8

James



More information about the Python-list mailing list