Creating instances of untrusted new-style classes

Devan L devlai at gmail.com
Thu May 25 21:06:09 EDT 2006


Is there any safe way to create an instance of an untrusted class
without consulting the class in any way? With old-style classes, I can
recreate an instance from another one without worrying about malicious
code (ignoring, for now, malicious code involving attribute access) as
shown below.

>>> import types
>>> class Foo:
...     def __init__(self, who, knows, what, args):
...         self.mystery_args = (who, knows, what, args)
...         print "Your code didn't expect the Spanish inquisition!"
...
>>> f = Foo('spam','eggs','ham','bacon') # This would be in a restricted environment, though.
Your code didn't expect the Spanish inquisition!
>>> types.InstanceType(Foo, f.__dict__) # This wouldn't, but we never run that code, anyways.
<__main__.Foo instance at 0x008B5FD0>
>>>

I'm not sure how to do the same for new-style classes, if it's at all
possible to do from within Python. Is there any way to accomplish this,
or is there no practical way to do so?

Thanks,
- Devan




More information about the Python-list mailing list