Static typing

Shane Hathaway shane at zope.com
Fri Jul 25 23:50:03 CEST 2003


Scott David Daniels wrote:
> You _might_ want some static typing information as program
> documentation or to enable efficient program translation.  The
> types sig was interested in allowing type annotation where
> possible.  Remember, the type you might want may be more like
> "what protocol must these objects (the ones passing through
> this variable) follow" than "what are the construction details
> of these objects".
> 
> I would like to see interface descriptions describing what
> kinds of parameters are required and results produced for
> packages that I am considering using.  If there were a single
> central-python-endorsed form for those descriptions even better.
> If the descriptions can be mechanically read, and at least
> sometimes mechincally checked (possibly slowly, possibly only
> for slow execution), I might use such a system to check a module
> before announcing it to the world.

Well, here's a pattern I've been trying out for this purpose: use assert 
statements at the top of the function.

def foo(bar, baz):
     assert isinstance(bar, int)
     assert isinstance(baz, str)

It has the following nice properties:

- The type checks are useful for debugging and can be optimized away.

- The intent is obvious.

- No changes to Python are necessary.

- You could easily parse the assert statements for type documentation 
(as long as the statements are kept simple.)

- It avoids the need for some kind of docstring markup language.

I'm quite happy with the pattern, although there are a couple of 
negative points that I can think of:

- It's a bit verbose, although that verbosity enables you to perform 
bounds checking and operate with other type systems like Zope's interfaces.

- You can't specify the type of the return values this way.

What do you think?  Should this become a common idiom?

Shane






More information about the Python-list mailing list