Variable class instantiation
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Dec 11 05:09:17 EST 2009
On Fri, 11 Dec 2009 10:26:49 +0100, Jan Mach wrote:
> I need to have the class name in the
> string and then instantiate it:
>
> (this does not work of course)
> classToUse = "C1"
> o = classToUse()
>
> It is because I don`t know at the moment what the name of the class will
> be, I will load it from the file or pass it as argument. Does anyone
> know what is the correct syntax to accomplish this?
Here are three solutions:
# 1
classToUse = globals()['C1']
# 2
thisModule = __import__(__name__)
classToUse = thisModule.__dict__['C1']
# 3
classToUse = eval('C1')
The first solution is probably the best; the third is tempting, but
dangerous if you can't absolutely trust the source of the string 'C1'.
(Google "code injection" for more details on why eval is risky.)
--
Steven
More information about the Python-list
mailing list