[Tutor] Re: compute class name

Magnus Lycka magnus@thinkware.se
Fri Nov 1 05:49:08 2002


At 17:18 2002-10-31 -0800, Emile van Sebille wrote:
>Ulrich Wisser:
> > I would like to create new object instances, but compute the
> > class name. Simple example
>    t = globals()[name]()

This is certainly safer than to use eval() that
I mentioned, at least if the string can be changed
outside the control of the programmer.

It's still not perfect though. Someone who could
change the string could still be able to execute
unexpected things defined in the global namespace.

The best option might be to register the classes
that are to be dynamically invoked in a dict, and
to invoke them from that dict.

 >>> classDict = {}
 >>> class A:
...     pass
...
 >>> class B:
...     pass
...
 >>> for klass in [A, B]:
...     classDict[klass.__name__] = klass
...
 >>> print classDict['A']()
<__main__.A instance at 0x0165FE10>
 >>> print classDict['B']()
<__main__.B instance at 0x00F2AA28>
 >>> print classDict['X']()
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
KeyError: X



-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se