Given the dynamic typing nature of Python, some developers use assertions at the top of their functions and methods to make sure the arguments have proper content, for example:
def divide(dividend, divisor): assert isinstance(dividend, (int, float)) assert isinstance(divisor, (int, float)) return dividend / divisor
This is often done by developers who are used to static typing and feel that something is missing in Python.
This way of checking arguments is a part of the Design by Contract (DbC) programming style, where preconditions are checked before the code is actually run.
The two main problems in this approach are as follows:
- DbC's code explains how it should be used, making it less readable
- This can make it slower, since the assertions are made on each call
The latter can be avoided with the -O option of the Python interpreter. In that case, all assertions are removed from the code before the byte code is created, so that the checking is lost.
In any case, assertions have to be done carefully, and should not be used to bend Python to a statically typed language. The only use case for this is to protect the code from being called nonsensically. If you really want to have some kind of static typing in Python, you should definitely try MyPy or a similar static type checker that does not affect your code runtime and allows you to provide type definitions in a more readable form as function and variable annotations.