Purpose of Python Type Checking?

jerf at compy.attbi.com jerf at compy.attbi.com
Mon Jan 27 05:56:58 CET 2003


On Sun, 26 Jan 2003 23:13:29 -0500, Terry Reedy wrote:
> 2. Situation-specific need such as changing behavior depending on
> type.
> 3. Application of belief in "look-before-you-leap" rather than
> "try-it-and-see".

I use it in my code generally as a combination of those two; I believe in
"try it and see, but if it fails it must fail atomically", i.e., a failure
does not change anything in the data structure. If I can not guarentee
this, I will do certain checks (usually just the type checking described
in the OP), which while you can never always truly *guarentee* that an
operation will succeed after those checks, you may be able to push the
occurance rate down to an acceptable level.

This especially happens when I'm creating an abstract OO API that I expect
others to fill in, and I have no control over the code that will execute,
nor do I wish to push responsibility for ensuring those properties onto
the programmer with no 'safety net' at all for detecting failures. (It is
their responsibility to meet the requirements, of course, but the more
help you offer them in doing it, the happier everybody is.) A subtle
failure to maintain some property might take the entire application down
with it and corrupt user data in difficult-to-debug or correct ways, so
IMHO it's worth the protection that a little 'look-before-you-leap' can
offer you in that case. (After all, losing user data is The Ultimate
Programming Sin, ranking well above Violating the Python Philosophy. ;-) )

Usually I leave an out, though, by declaring an empty "Tag" class from
which my top-level class derives, and checking against that rather then
the top-level class, so if someone REALLY knows what they are doing, they
can still write a class with that interface from scratch. (Which reminds
me I need to fix that in my code...) It is then easy enough to add that
tag class to any other class, even pre-existing ones, to deliberately
'bypass' the type checks.





More information about the Python-list mailing list