Dynamically replacing an objects __class__; is it safe?

Steve D'Aprano steve+python at pearwood.info
Thu Mar 16 08:06:48 EDT 2017


On Thu, 16 Mar 2017 09:03 am, Gregory Ewing wrote:

> Steve D'Aprano wrote:
>> You probably can't make a whale fly just by changing the class to bird.
>> It will need wings, and feathers, at the very least.
> 
> Some things succeed in flying with neither wings nor feathers.
> Helicopters, for example.

For some definition of "no wings".

But regardless of rockets, balloons, helicopters, Boeing 747s and Dr
Strange's mystical Cloak Of Levitation, *birds* require wings and feathers
to fly. If you just paint "BIRD" on the side of a whale, it won't get off
the ground, and if you do manage to get it airborne (via a catapult,
perhaps) it will just come down with a rather large splat.

The point is that dynamically swapping the class of an existing instance at
runtime is *not* just a way of doing duck-typing. It really does matter if
your duck flies by flapping feathered wings or by blasting an exhaust of
hot gasses out of its rear end at high speed.

With duck-typing, you don't care whether you have a duck or a goose, so long
as they both can fly: you don't care *how* it flies, so long as it does,
and even a rocket-propelled balloon will be fine.

But when you dynamically swap out __class__ (I think Objective-C "swizzling"
is conceptually equivalent, so I'll call it by that word) you have to care
about the implementation. The whole point of swizzling is that it allows
you to swap out one implementation ("run forward and flap your wings") with
another implementation ("light the blue touch paper"). But if you do that,
you have to care about implementation details. There's no point in setting
your swizzled fly() method to that of Rocket if your instance doesn't have
blue touch paper to light.

With duck-typing, making the methods work isn't your responsibility. But
when you swizzle, you are responsible for making sure that the instance
provides whatever the methods need to work.

A very old but good example of Python swizzling is here:

http://code.activestate.com/recipes/68429-ring-buffer/



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.



More information about the Python-list mailing list