What is dynamic dispatch and duck typing?

Rick M. picture Rick M. · Feb 14, 2018 · Viewed 21.2k times · Source

When using Pycharm, It often points out an error, saying:

Unresolved reference 'name'. This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items.

I've snooped around about this, but most questions and information I find is about preventing the message from being shown. what I want to know is:

  • What is dynamic dispatch/duck typing?
  • What are (or an example of) these "useful number of cases"?

Answer

smallpants picture smallpants · Feb 16, 2018

Python uses a duck typing convention. This means that you do not have to specify what type a name is. Unlike in Java, for example, where you must specify explicitly that variable may be type int or Object. Essentially, type checking is done at runtime.

"If it walks like a duck and it quacks like a duck, then it must be a duck."

In Python everything will seem to work until you use try to manipulate an object in a way that it is not designed to. Basically, an object may not have a certain method or attribute that another might, and you won't find this out until Python throws an error upon trying it.

Dynamic Dispatch is the practice of the compiler or environment choosing which version of a polymorphic function to use at runtime. If you have multiple implementations of a method, you can use them in different ways despite the methods having the same or similar properties/attributes. Here's an example:

class Foo:
   def flush():
       pass

class Bar:
    def flush():
       pass

Both classes have a flush() method but the correct name is chosen at runtime.

Python is not the best example of this process since methods can take multiple parameters and don't have to be reimplemented. Java is a better example, but I'm not fluent enough in it to provide a correct example.