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

2

7

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.

Mcloughlin answered 23/12, 2016 at 16:53 Comment(4)
Why should you check that your method is receivng a numeric type? If it doesn't, all you can do is raise some kind of exception; but an exception would already be raised if you tried to do an arithmetic operation on a type that doesn't support it. So what's the point of checking explicitly?Lakesha
Related - #1950886Capuano
Possible duplicate of Should I force Python type checking?Endothelioma
@Endothelioma that answer focuses more on why you shouldn't do it in general. I'm looking more for specifically when (if ever) you should.Mcloughlin
D
6

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.

Dumas answered 23/12, 2016 at 17:0 Comment(2)
Just for the record, some background for the term duck-typing: https://mcmap.net/q/24990/-what-is-duck-typingHeteroecious
The problem typically is that you ask it to quack only when the user frobs the widget in that particular way, and so you discover that somebody passed a Dog instead of a Duck only during the most important demo ever.Paulpaula
F
0

The simple answer is probably start without any typechecking and see what happens. You'll probably find out - as I did 17 years ago and much to my surprise - that you need it way less than you believe. For the record used to think you couldn't hope to write anything but quick scripts and toy programs without strict typechecking and lost a lot of time fighting against the language until I started reading serious python apps code and the stdlib code and found out it just worked without.

Frisket answered 23/12, 2016 at 19:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.