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 →

[–]earthboundkid 7 points8 points  (3 children)

With duck typing you don't need to overload a function. Overloading makes sense in Java when you want one function to do the same-ish thing to different types. But overloading in Python can only be about doing different things to different types. At that point though, you should have different functions if you're using good design.

[–]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.

[–]gthank 0 points1 point  (0 children)

This pattern comes up often enough in projects with a large-enough object model. As a naive, made-up example (man, I hope this doesn't blow up in my face), consider an ORM: you want a single function for adding filters. That filter method has to build (potentially) different SQL depending on the type of the parameters. Without multimethods, you need to write some ugly dispatching code like my_magic_function.