Purpose of Python Type Checking?

Alex Martelli aleax at aleax.it
Mon Jan 27 08:25:23 CET 2003

jerf at compy.attbi.com wrote:

> 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

I find a (very occasional) need for such "low-level atomicity" (more
often the atomicity must be ensured as part of a larger transaction
in an ACID context and thus it's not very useful to bend over backwards
to also guarantee it to such fine granularity), and have documented
the approach as a recipe in the Python Cookbook, online at:

I've named this approach "_Accurate_ look-before-you-leap".  There
is a more detailed analysis and explanation of it in the O'Reilly
printed version of the Python Cookbook, of course.  But the key issue
is that even in such very occasional situations type-checking is
hardly ever the best way -- rather, *feature-checking* (checking
that objects have the needed attributes and that certain operations
can be performed with them) is generally superior, in the same vein:

> 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.

...i.e., no guarantees, but better chances of "high-granularity
atomicity", and WITHOUT all the costs imposed by type-checking.

> 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

But this means they still cannot use an otherwise perfectly acceptable
object they get from somewhere else -- they still have to wrap it with
a delegating-class instance just for the "boilerplate" satisfaction of
making your typechecks happy.  Not optimal, IMHO, except perhaps in a
tiny subset of such already pretty-rare cases.

Generalized protocol-adaptation would go a very long way towards making
such debates moot, of course -- but as it doesn't seem likely we'll get
it any time soon, I think it's preferable to keep warning most coders
against the instinctive-but-inferior impulse to typecheck.


More information about the Python-list mailing list