string to variable name

Alexander Schmolck a.schmolck at gmx.net
Thu Apr 24 20:02:52 EDT 2003


>   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]]))

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

> Hey! Could I do it by overloading the special function that's called when you
> treat something like a dictionary?  i.e. could I make my class respond to 
>   key = "bar"
>   inst[key] = "baz"
> as though it got
>   inst.bar = "baz"

Sure.

> 
> How?

if you really feel the need, have a look at __setitem__ in the python language
reference

'as




More information about the Python-list mailing list