Creating instances of untrusted new-style classes

Devan L devlai at gmail.com
Fri May 26 01:01:06 EDT 2006


Michael Spencer wrote:
> Devan L wrote:
> > 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.
> >
[snip my example]
> >
> > 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
> >
>  >>> class A(object):
> ...     def __init__(self, *args):
> ...         self.args = args
> ...         print "Calling __init__"
> ...
>  >>> a = A("new","style")
> Calling __init__
>  >>> b = object.__new__(A)
>  >>> b.__dict__ = a.__dict__.copy()
>  >>> b.args
> ('new', 'style')
>  >>> type(a) is type(b)
> True
>  >>>
>
> HTH
>
> Michael

Thanks, now I just have to figure out all the meddling small details I
put off before!

-Devan




More information about the Python-list mailing list