make a class instance from a string ?

Scott David Daniels scott.daniels at acm.org
Fri Feb 24 10:54:39 EST 2006


Mike Woodhouse wrote:
> Is there anything particularly bad with
>       obj = eval(classname + "()")
> It appears to work, but I'm a noobie so I could be missing something
> nasty, in which any edication would be gratefully received.

It is a little too indirect.  Usually wanting to use "eval" or "exec"
means your code is probably not properly structured (a "code smell").
You can pass classes around as values; you typically needn't work with
their names.  If the name comes from outside, a dictionary of names to
classes means you can re-implement your code without being tightly
coupled to your I/O formats.  If you still want to use the name
I'd go with:
         globals()[classname]()
over eval, but it is your code.

Here's a danger to think about:
Suppose your source of class names has:
     '__import__(os).system("delete critical.file")'
for a class name?


--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list