Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Variable class instantiation

0 views
Skip to first unread message

Jan Mach

unread,
Dec 11, 2009, 4:26:49 AM12/11/09
to pytho...@python.org
Hi everybody,
I am currently solving the following problem and I am stuck. I am trying
to create instance of the class of variable name. I know, that the
following works:

if (something):
classToUse = C1
else:
classToUse = C2

o = classToUse()

,but this is not what I want. 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?

Thanks for your time in advance

Jan Mach

Richard Thomas

unread,
Dec 11, 2009, 5:06:35 AM12/11/09
to
>  smime.p7s
> 4KViewDownload

You can always do eval(my_string) to get the class object.

Better I think is to make an explicit dictionary of options (much
safer).

classes = dict((cls.__name__, cls) for cls in (C1, C2))
classes["C1"] # gives you C1
classes["C2"] # gives you C2

Richard.

Steven D'Aprano

unread,
Dec 11, 2009, 5:09:17 AM12/11/09
to
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

Lie Ryan

unread,
Dec 11, 2009, 5:10:48 AM12/11/09
to

Make a dict of name->class, otherwise it's a security issue. A malicious
user may pass a class you never wish to instantiate (with eval, it's
even worse, malicious user can execute arbitrary code).

Sion Arrowsmith

unread,
Dec 11, 2009, 6:36:13 AM12/11/09
to
Steven D'Aprano <st...@REMOVE-THIS-cybersource.com.au> wrote:
>thisModule = __import__(__name__)
>classToUse = thisModule.__dict__['C1']

Any reason to prefer this over:

classToUse = getattr(thisModule, 'C1')

? (I think, for a module, they should do exactly the same thing.
Personally, I prefer keeping explicit references to __special
names__ to a minimum.)

--
\S

under construction

Steven D'Aprano

unread,
Dec 11, 2009, 6:40:14 AM12/11/09
to

No, no reason at all. I just forgot about getttr.

--
Steven

0 new messages