strings question

Peter Hansen peter at
Fri Mar 12 19:42:06 CET 2004

Faheem Mitha wrote:

> Dear People,
> If I am given two strings, named foo and bar, what is the most elegant
> way to create a string object whose name is the value of foo and whose
> value is the value of bar? I have done some searching + looking in my
> introductory textbook "Learning Python" but have not come up with an
> answer yet.

Assuming this is inside a method and not a function:

     def makeAttribute(self, foo, bar):
         setattr(self, foo, bar)

will do the trick.

If you need it in a function, use globals() as a dictionary, but note 
that you are getting a global, not a local.  You can't do it effectively 
if what you want is a local.


More information about the Python-list mailing list