make a class instance from a string ?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Feb 24 11:07:59 EST 2006


On Fri, 24 Feb 2006 06:37:27 -0800, 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.

In your own code, that you control? Nothing particularly bad.

In your public web application, using classname supplied by some anonymous
remote user? It could be bad:

obj = eval("(lambda : os.system('ls'))" + "()")

only, instead of 'ls', imagine a more... serious shell command.

Using eval is like running a small piece of Python code. If you control
the code (or to be precise, the expression) then it is no more dangerous
than any other code you choose to run.

On the other hand, if you give access to your system to anonymous users,
you have to assume some of them will be malicious, and they will be a lot
more inventive searching for security holes than you.


-- 
Steven.




More information about the Python-list mailing list