string to variable name

Gerhard Häring gh at ghaering.de
Thu Apr 24 19:21:22 EDT 2003


Benjamin Hartshorne wrote:
> <disclaimer -- perl programmer trying to learn python>
> 
> I'm trying to figure out how to get from a string to a varible name.  I just
> picked up Python last week, so I'm still kinda new at this. 
> 
> Suppose I've got a text file:
> 
> """
> blah blerg blarf
> foo bar baz
> spam eggs ham
> """
> 
> I have a class:
> 
> class myobject:
>   def __init__(self):
>     self.blerg = "blarf"
>     self.bar = "baz"
>     self.eggs = "ham"
> 
> I have a global:
> 
> inst = myobject()
> 
> I have a function that I want to change the variables in my class:
> 
> def myassigner():
>   file = open("mytextfile", 'r')
>   for line in file.readline():
>     m = re.match("^(\w+)\s+(\w+)\s+(\w+)$", line)
>     (newval, var, oldval) = m.groups()
>     inst.var = newval
> 
> The equivelent (of what I _want_ to do) in perl: [...]
>     inst.$2 = $1;
>  [...]

Use setattr:

setattr(inst, var, value)

You can easily guess what getattr and hasattr will do.

> [...]
> p.s.  The inspiration behind asking this question: I want to store all the
> values passed in by a CGI script in an instance of a class.
> 
> for key in mycgi.keys():
>   mystorage.key = mycgi[key].value

I'd suggest you only overwrite attributes you have in a particular list, 
otherwise somebody could enerve you by submitting a variable called 
"__init__" or something like that ;-)

So, something like (untested):

class MyClass:
     __cgi_vars = ["foo", "bar", "baz"]
     def __init__(self):
	...


myobject = MyClass()

for key, value in mycgi.items():
     if key in MyClass.__cgi_vars:
         setattr(myobject, key, values)

> 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"
> 
> How?

Sure, overload the __setattr__ and __getattr__ and for extra fun, the 
__contains__ special methods. See 
http://www.python.org/doc/current/ref/attribute-access.html

__contains__ will affect the "in" operator and is described in
http://www.python.org/doc/current/ref/sequence-methods.html

These and the pages nearby show you how dynamic you can make Python, 
including making custom callables, new numeric types, ...

If you're using Python 2.2, you might also be interested in using 
properties.

-- Gerhard





More information about the Python-list mailing list