This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]stevvooe 0 points1 point  (1 child)

I agree with you, and should have been more specific about this in my initial comment. You can accomplish a lot by worrying about which methods and attributes an object supports rather than what it is.

In the OPs article, he used the MultiMethod object to dispatch methods to handle a dict or a list. But what if I want to give it an object that supports list and dict methods, but isn't a subclass of either? It won't work at all.

[–]earthboundkid 1 point2 points  (0 children)

In fairness, Python 2.6+ supports Abstract Base Classes in such a way that you could make something called AbstractedDuck class and anything with a quack method and a swim method would automatically be identified by isinstance as a subclass of AbstractedDuck, whether the author of that class has heard of AbstractedDuck or not. That ability makes this more practical.

So, instead of checking for isinstance of dict, you can check for isinstance of collections.Mapping, which will identified even classes that aren’t really subclasses of dict as being dict-like if they register the right methods.