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

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

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

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:

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.

Post a Comment