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

I am starting to learn Python and, as a developer first of all, Java, the biggest problem that I encounter is to understand when and when not to use type checking. Most people seem to say that Python code does not need type checking, but there are many cases where I find it necessary. For example, let's say I need to use a method parameter to perform an arithmetic operation, why not make sure that the argument is a numeric data type?

This problem is not limited to functions only. The same thought process arises for class variables. Why and when should I or should not use properties (using @property ) to check type instead of regular class variables?

This is a new way to approach development for me, so I would appreciate understanding.

+5
source share
2 answers

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

 def quack(duck): duck.quack() 

this will only be done if duck has the called quack attrubute, this will throw an exception that can be caught by the caller.

+5
source

The simple answer probably starts without any type checking and see what happens. You will probably find out how I did it 17 years ago, and to my surprise, you need it less than you think. For the record you were counting, you cannot hope to write anything other than quick scripts and toy programs without strict type checking, and you lost a lot of time struggling with the language until I started reading serious python application code and stdlib code and found out it just worked without.

0
source

Source: https://habr.com/ru/post/1261791/


All Articles