Newbie: static typing?

Steven D'Aprano steve at pearwood.info
Tue Aug 6 05:26:50 EDT 2013


On Tue, 06 Aug 2013 10:05:57 +0100, Rui Maciel wrote:

> What's the Python way of dealing with objects being passed to a function
> that aren't of a certain type, have specific attributes of a specific
> type, nor support a specific interface?

Raise TypeError, or just let the failure occurs however it occurs, 
depending on how much you care about early failure.

Worst:

if type(obj) is not int:
    raise TypeError("obj must be an int")


Better, because it allows subclasses:

if not isinstance(obj, int):
    raise TypeError("obj must be an int")


Better still:

import numbers
if not isinstance(obj, numbers.Integer):
    raise TypeError("obj must be an integer number")



All of the above is "look before you leap". Under many circumstances, it 
is "better to ask for forgiveness than permission" by just catching the 
exception:

try:
    flag = obj & 8
except TypeError:
    flag = False


Or just don't do anything:


flag = obj & 8


If obj is the wrong type, you will get a perfectly fine exception at run-
time. Why do extra work do try to detect the failure when Python will do 
it for you?



-- 
Steven



More information about the Python-list mailing list