Dynamically replacing an objects __class__; is it safe?

marco.nawijn at colosso.nl marco.nawijn at colosso.nl
Wed Mar 15 06:55:47 EDT 2017


On Wednesday, March 15, 2017 at 11:33:56 AM UTC+1, Peter Otten wrote:
> marco.nawijn at colosso.nl wrote:
> 
> > Dear All,
> > 
> > Summary of the question:
> > Is it generally safe to dynamically change an objects class; if not
> > under which conditions can it be considered safe.
> > 
> > Context:
> > Given the code below, I have no direct control over Base and M1. M1
> > is a instantiated by 'calling' the read-only property of Base.
> > I would like to transparently switch behaviour from M1 to M2. I have
> > tried several things, but finally settled on the code below. Although
> > it works really well, I am not sure whether I am about to shoot myself
> > in the foot. In short, what I do is derive from Base, shadow the read-only
> > property 'my_prop' so it returns M2 and finally replace an objects
> > __class__ attribute with my derived class.
> > 
> > Any thoughts or comments?
> 
> Saying that something is "safe" is always problematic. I'd rather look for 
> ways to break the code and then decide if you can live with these potential 
> problems. I'll start with
> 
> - If Base is reimplemented in C __class__ may become read-only
> - my_prop may be accessed by Base methods and expect an M1 instance

Ok. These are valid points. The first is not a real concern to me at the
moment. The whole purpose of Base is to provide a higher level interface
to the underlying C/C++ code.

The second is more interesting. I was aware of this and checked the source
code of the library. I know an M1 instance is not directly used by Base.
In addition, I expose the exact same interface in M2. 

Thanks for the feedback. Much appreciated!

Marco


More information about the Python-list mailing list