Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use type checking (if ever) in Python?

I'm starting to learn Python and as a primarily Java developer the biggest issue I am having is understanding when and when not to use type checking. Most people seem to be saying that Python code shouldn't need type checking, but there are many cases when I believe it is necessary. For example, let's say I need to use a method parameter to perform an arithmetic operation, why shouldn't I make sure the argument is a numeric data type?

This issue is not only limited to functions. The same thought process occurs to me for class variables. Why and when should I or shouldn't I use properties (using @property) to check type instead of regularly implemented class variables?

This is a new way of approaching development for me so I would appreciate help understanding.

like image 668
cbender Avatar asked Dec 23 '16 16:12

cbender


People also ask

Should I do type checking in Python?

Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.

What does type checking do in Python?

Python is both a strongly and dynamically typed programming language. This means that any variable can take on any data type at any time (this is dynamically typed), but once a variable is assigned with a type, it can not change in unexpected ways.

What are reasons for using type hinting?

Type hints help document your code. Traditionally, you would use docstrings if you wanted to document the expected types of a function's arguments. This works, but as there is no standard for docstrings (despite PEP 257), they can't be easily used for automatic checks. Type hints improve IDEs and linters.

How do you ensure type safety in Python?

You can enforce type safety in your programs manually by checking types of inputs. Because everything is an object, you can always create classes that derive from base classes, and use the isinstance function to verify the type (at runtime of course). Python 3 has added type hints, but this is not enforced.


1 Answers

It's not Pythonic to check type info, use duck typing instead: if it looks like a duck, walks like a duck and quacks like a duck then it is a duck.

def quack(duck):
    duck.quack()

this will only run if duck has a callable quack attrubute, it will raise an exception otherwise which can be caught by the caller.

like image 129
Paul Evans Avatar answered Oct 25 '22 15:10

Paul Evans