string to variable name

Benjamin Hartshorne ben at hal.rescomp.berkeley.edu
Fri Apr 25 01:04:40 CEST 2003


<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:

sub myassigner() {
  FILE = open("<mytextfile");
  while (<FILE>){
    /^(\w+)\s+(\w+)\s+(\w+)$/;
    inst.$2 = $1;
  }
}

But, as I'm sure you're all aware, the python does not do what the perl does.
Instead, it writes newval into a variable in inst called 'var'.  

Is there any way to (easily) achieve what I want to do in python?

Thanks,

-ben

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

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?

-- 


-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Ben Hartshorne




More information about the Python-list mailing list