string to variable name

Alex Martelli aleax at aleax.it
Fri Apr 25 06:59:13 EDT 2003


Alexander Schmolck wrote:

>>   FILE = open("<mytextfile");
>>   while (<FILE>){
>>     /^(\w+)\s+(\w+)\s+(\w+)$/;
>>     inst.$2 = $1;
>>   }
>> }
> 
> 
>> Is there any way to (easily) achieve what I want to do in python?
> 
> Sure: you can do it even shorter and almost as unreadably with (UNTESTED):
> 
> for line in file("mytextfile"):
>     inst.__dict__.update(dict([line.split()[:2]]))

<shudder>:-).  Not to mention a likely key/value exchange.  Since lists 
can't be general-sliced in Python 2.2 (only in 2.3), in the spirit of this
solution, I propose using, as update's argument [ALSO UNTESTED]:
    dict([(lambda x,y: y,x)(*(line.split()[:-1]))])

Now THAT should warm the cockles of any Perlist's heart!


Now, joking apart...:

> a better way would be to use ``setattr(inst, key, value)``

Absolutely better -- for completeness, the loop should then be:

    for line in file('mytextfile'):
        value, key, junk = line.split()
        setattr(inst, key, value)


Alex





More information about the Python-list mailing list