nice python solution
Chris Liechti
cliechti at gmx.net
Sun Nov 18 17:20:55 EST 2001
[posted and mailed]
Uwe Schmitt <uwe at rocksport.de> wrote in news:9t95gu$ab7l1$1 at hades.rz.uni-
sb.de:
> Hi,
>
> i there a nice python shortcut for:
> if idx=0:
> a=val
> elif idx=1:
> b=val
>
> ???
> I tried
> (a,b)[idx] = val
>
> but this does not work, i get an error message.
>
> Greetings, Uwe.
if you have an object:
setattr(obj,('a','b')[idx], val)
or a bit uglier
obj.__dict__[('a','b')[idx]] = val
some hacky tries:
if a and b are initalized: a,b = idx and (a,val) or (val,b)
if repr gives a valid python expr.: exec '%s=%s'%('a','b')[idx], repr(val))
the cleanest i can find for globals is:
import __main__
__main__.__dict__[('a','b')[idx]] = val
depends on your situation, but maybe its easier to use a dict to store the
values.
d = {}
d[('a','b')[idx]] = val
tell us more about the situation were you use it, maybe there is a complete
other way to achieve the desired results.
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list