Monday, May 15, 2006

Optional typechecking: fun with "with"

A while ago, prompted by various entries [1, 2, 3, 4] on Guido's blog about Adding Optional Static Typing to Python, I mused about different ways of doing this [5, 6, 7], keeping the syntax as Pythonic as possible, but at the cost of introducing a new keyword ("where"). Today's entry is written in the same spirit (i.e. just for fun), but with a different syntax, and makes use of the new "with" keyword. By itself, this blog entry is probably too brief to make much sense.

Let me start by introducing some static typing information that could be extracted from an IDE, or used by pychecker or pylint.

01 def gcd(a, b):
02 '''Returns the Greatest Common Divisor,
03 implementing Euclid's algorithm.
04 with __typecheck__:
05 assert isinstance(a, int), 'First argument must be an integer.'
06 assert isinstance(b, int), 'Second argument must be an integer.'
07 #Some doctests for good measure
08 >>> print gcd(6, 3)
09 3
07 '''
08 while a:
09 a, b = b%a, a
10 return b
The above is totally valid Python. Just like doctests can be extracted by the doctest module, the "typecheck" assertions could be extracted and used by other programs. However, as they stand, they are "totally optional".

Now, if we wanted to use the typechecking information in some module where gcd() is actually used, we would have to instruct the interpreter to do so ... here's a way we might want to write this:
1    with __typecheck__:
2 gcd()
3 some_other_useful_function()
4 # the rest of the code follows...


Granted, this is not currently valid in Python ... but its intent should be understandable!

1 comment:

Anonymous said...

MY biggest issues I have with this are the same ones I have with all intrepted doc string implementations.

#1. all decorators (especially pass through) need to know about them and copy the doc string to the new decoration wrapper.

#2. again with decorators, in this example, they would need to know to add the 'with __typecheck__' inside the wrapper implementation. (well ok, this depends on how __typecheck__ is implemented).

#3. No proper basic syntax checking. This is my biggest complaint with any doc string hack like this.

I would perfer a decorator which describes the argiments and adds the type checking at that level. This has the bennifit of also being valid python, can be made optional (with the with statement if you so wish, or with some other means), and is just as obvious.