turning a string into an object name

Jeff Shannon jeff at ccvcorp.com
Thu Apr 4 14:15:01 EST 2002


In article <3cabf705.91920985 at mammoth.usenet-access.com>, 
netzapper at magicstar.net says...
> On 4 Apr 2002 00:58:10 GMT, Marco Herrn <herrn at gmx.net> wrote:
> 
> >Hello. I know that it is possible to turn a string into a funtion call by
> >using getattr(). But what I want to achieve is turning a string into an
> >object name. 
> >I would have a method like
> >
> >  foo(self, objname, objtype)
> >
> >Then I would call this method like
> >  
> >  foo(myObj, bar)
> >
> >Then the method foo should create an object with the name "myObj" from the
> >type bar.
> >
> >Is such an thing possible? And if, how?
> 
> I'll probably get blasted for this by Python gurus... but, I've used
> it with some success.  You can do
> 
> exec(myObjc + " = " + value)

You *can* do this, but using exec is asking for trouble someday.  
It's like pointers in C -- can be very useful, but can also cause 
lots of problems when somehow, something that you don't expect 
ends up getting in there (and if you use it much, that *will* 
happen).  There's a reason that C++ introduces (numerous flavors 
of) safe pointers, and new/delete to hide malloc()... and why 
languages like Python hide all forms of memory management.  
Typically, in Python, there are few things that can be done with 
exec/eval(), that can't be done better some other way.  (Not to 
mention that exec/eval() typically is ugly and hard to read, and 
therefore difficult to maintain...)

In the O.P.'s case, I'd ask, why do you want to create a top-
level variable?  I don't know your specific application, so this 
may not be the best solution, but I'd most likely try saving any 
objects created like this into a dictionary, like so:

MyObj = 'MyDesiredName'
class bar:
    pass

objects = {}
objects[MyObj] = bar()

You could also accomplish much the same thing by making objects 
into an empty class, and using setattr():

class ObjectHolder:
    pass

obj = ObjectHolder()
setattr(obj, MyObj, bar())

This requires a little bit more indirection than directly 
creating a variable from the string in MyObj, but it's safer, and 
often more convenient -- if I'm creating variables from strings, 
then I'm probably creating a group of them, and it makes sense to 
keep track of them as a group.

-- 

Jeff Shannon
Technician/Programmer
Credit International



More information about the Python-list mailing list