Adding static typing to Python
gbreed at cix.compulink.co.uk
gbreed at cix.compulink.co.uk
Wed Feb 20 12:12:36 EST 2002
Alexander Jerusalem wrote:
> I just looked up what CLOS does. I don't know if you call that static
> typing or not. In any case, CLOS does have type declarations in the
> source code which is what I want and what enables the features I'd
> like to see in Python. For example in CLOS you can have the following
> method declarations:
>
> (defmethod Area ((C Circle)) (* pi (Square (Radius C)))
> (defmethod Area ((R Rectangle)) (* (Width R) (Height R)))
> (defmethod Area ((Sq Square)) (Square (Width Sq)))
> OR (defmethod Height ((Sq Square)) (Width Sq))
But you can do that in Python:
>>> def area(shape):
... if isinstance(shape, Circle):
... return math.pi*shape.radius**2
... if isinstance(shape, Rectangle):
... return shape.width*shape.height
... if isinstance(shape, Square):
... return shape.width**2
... raise TypeError, "unknown shape"
...
It can't take much imagination to see how it could be sugared to work with
multiple functions with types resolved at run time. As for strict,
strong, static, explicit typing (which may be a straw man) it looks *less*
suitable for this example.
Say you want to include a triangle in your list of shapes. So, you add
... if isinstance(shape, Triangle):
... return shape.base*shape.height
to the area function. But then, will all the other functions that call
area be allowed to accept a triangle? If they're defined to accept either
circles, rectangles or squares, you'll have to change each one's interface
to allow triangles as well.
You could make them all subclasses of Shape. In which case, you have
functions defined to use a polymorphic object that depend on function
overloading by the real type. Not all statically typed languages will
allow that. If they do, you have the problem that you might have added
triangles for some other reason, and forgotten to cater for them in
area(). You aren't getting static type checking at all.
Wouldn't it be better to make area a method of the shapes? And for static
typing, make it abstract in the Shape class?
Graham
(http://www.microtonal.co.uk/)
More information about the Python-list
mailing list