So others answered in ways to generally catch exceptions. I'm going to bend a little differently. I think you are asking about how you can achieve the same type safety as in a statically typed language.
First, you probably don't want this. One of the advantages of python is duck printing . Material from Wikipedia:
duck typing is a dynamic typing style in which the current set of methods and properties of an object determines the actual semantics, and not its inheritance from a particular class or implementation of a specific interface
The advantage of duck printing is that you do not need to perform type checking, you can pass any object that has this method.
However, you have a problem: "How to consistently check the correctness of my code without running it?" This is especially annoying when an error occurs only in the case of an edge. One good way to ensure consistent behavior, even when changing the code base, is to write unit tests . Python has several different ways to implement unit testing. The simplest may be the doctest module. However, if you want something more powerful, unittest , and a compatible third-party nose structure.
The advantage of unit testing is that you can write them along the way, making sure to look for even unusual extreme cases, and then run them anytime you make significant changes to your program. Then, if the tests fail, you know that something is broken.
source share