Does Python PEP support the polymorphism concept

What are the differences between type () and isinstance ()?

Differences between and in Python?

Type test with

allows instances of subclasses and several possible bases:

while the type test with

only supports the specified type.

As a side note is probably more appropriate than

because classes are singletons.

Avoid type checking - use polymorphism (duck typing)

Typically in Python you want to allow any type for your arguments, treat it as expected, and throw an appropriate error if the object does not behave as expected. This is known as polymorphism, also known as duck typing.

If the above code works, we can assume our argument is a duck. Thus, in other things, we can pass on actual subspecies of ducks:

or that works like a duck:

and our code still works.

However, there are some cases where explicit type checking is desirable. Perhaps you have reasonable things to do with different types of objects. For example, the dataframe object pandas can be made from dictation or Records are created. In such a case, your code needs to know what kind of argument it is receiving in order to handle it properly.

So, to answer the question:

Differences between and in Python?

Let me demonstrate the difference:

Suppose you need to ensure certain behavior when your function takes a certain type of argument (a common use case for constructors). If you're looking for a guy like this:

If we try to pass on a dictation that is a subclass of (as we should if we expect our code to follow the principle of Liskov substitution) these subtypes can be replaced by types) our code breaks!:

throws an error!

But if we use we can support Liskov substitution!:


Abstract base classes

In fact, we can do better. provides abstract base classes that enforce minimal protocols for different types. In our case, if we just expect the log, here's what we can do, and our code becomes even more flexible:

Reply to comment:

Note that the type can be used to check against multiple classes.

Yes, you can test for equality of types. However, instead of the above, use the multiple bases for control flow unless you specifically allow only the following types:

The difference, again, is that it supports subclasses that can be replaced by the parent classes without otherwise damaging the program. This property is known as the Liskov substitution.

However, it is even better to invert the dependencies and not look for specific types at all.


Since we want to support the replacement of subclasses, in most cases we want to avoid type checking with and prefer type checking with - unless you really need to know the exact class of an instance.