type-checking support in Python?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Mon Oct 6 18:14:52 CEST 2008

Joe Strout a écrit :
> 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,

Good naming and documentation.

> in a uniform manner; and (b) 
> catch any type errors as early and automatically as possible.

For which definition of "type error" ?-)

To make a long story short, duck typing is the pythonic way to do 
things. From experience, type errors are rare, and usually very quickly 
spotted and fixed. Except when it comes to handling user inputs, don't 
bother coding in a defensive style. Just write the minimal necessary 
code, and only worry about exceptions you somehow except *and* can 
handle locally.

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

yes : unittests.

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

Not AFAIK. This may come with py3k using ABCs and type annotations, but 
once again, don't worry too much about this.

I know these advices may sound scary to declarative static typing 
addicts, but man/years of experience have proven that duck typing 
JustWork(tm). So don't fight the language, it would only make you suffer 
useless pain and frustration.

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

Then you can already prefix each and any of your identifiers (including 
classes and functions) with an 'o', since everything in Python is an 
object !-)

>  I gather (from just a couple days of browsing) that such a 
> naming convention isn't common in the Python community,

It's not only uncommon, but - just like useless typechecking - 
considered bad form.

> 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 standard coding conventions are here:

FWIW, Python relies quite heavily on naming conventions. Better to stick 
to pep8.

More information about the Python-list mailing list