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.
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.
this will only run if
duck
has a callablequack
attrubute, it will raise an exception otherwise which can be caught by the caller.