type-checking support in Python?

Diez B. Roggisch deets at nospam.web.de
Mon Oct 6 10:46:26 EDT 2008


Joe Strout wrote:

> I'm just re-learning Python after nearly a decade away.  I've learned
> a good healthy paranoia about my code in that time, and so one thing
> I'd like to add to my Python habits is a way to both (a) make intended
> types clear to the human reader of the code, in a uniform manner; and
> (b) catch any type errors as early and automatically as possible.
> 
> I found the "typecheck" module (http://oakwinter.com/code/typecheck/),
> but I notice that it hasn't been updated since 2006, and it's not
> included with the Python distribution.  Are there other modules
> providing similar functionality that I should consider instead?
> 
> Also, I'll probably be considering a lint-like tool at some point...
> are there any that allow you to declare some extra type information,
> and have that checked at lint time?
> 
> Finally, one thing I've considered is adopting some identifier
> prefixes indicating type.  Maybe "iFoo" for integer, "fFoo" for
> floating-point numbers, "d" for dictionary, "l" for list, "t" for
> tuple, "o" for object, and "v" for variable types that may be more
> than one of the above.  I gather (from just a couple days of browsing)
> that such a naming convention isn't common in the Python community,
> but is there anyone else here who does it?  I'd rather adopt an
> existing standard (even if it's not widely used) than make one up.

The short answer is:

 - don't use typechecks, or at least as few as possible - only for
polymorphy. Ducktyping is important for good python code, and shouldn't be
prevented by excessive typechecks.

 - if you don't trust your code, write tests. Actually, *always* write
tests. It really helps getting the design of your code better, saves time
when refactorings or enhancements are needed - and captures more errors
that static typechecking - and your typechecking actually isn't even static
& thus you'd need tests to get code coverage anyway.

 - don't adopt these silly microsoft perversion of hungarian notation.
clear, expressive variable names - sure. with pre- or suffixes to indicate
their kind, possible. But using iX or fX where all one cares is that X
holds a number is not helpful.

Diez



More information about the Python-list mailing list