Re: Adding Optional Static Typing to Python
Posted: Dec 28, 2004 2:47 PM
Some semi-random comments about static typing in Python:
O'Caml provides a nice example of how static duck typing can be done. The problem with it, though, is that writing the types explicitly can be quite tricky. The typing is best left to the type inferencer. If used in Python, I'd suggest that you don't allow for explicit typing, since it would make the code very unreadable. Of course, no type inferencer is 100% accurate, so if explicit types aren't allowed, the type checker would have to emit warnings instead of errors.
Code written like this would wreak havoc with any static type checker, both explicit and inferred:
def divide(x : int) -> int:
return x / 2
def new_divide(x : str) -> str:
divide = new_divide
This is obviously a contrived example, but one of the useful features of Python is that it is so dynamic that you can redefine methods and functions at runtime.
Again, the solution to this is to have the type checker only emit warnings instead of errors, or perform the type-checking at runtime when the function is called.
Warnings vs. Errors
How, exactly, would a Python compiler perform static type checking without throwing an exception? (That is, only emit type warnings, not errors.) Currently, syntax errors are reported as exceptions when the module is first imported. How would type warnings be reported? Should the compiler be allowed to write a message to stderr and screw up any interface that might be displayed on the command line? Provide continuable exceptions? Maybe it just invokes some callback that can be replaced, like sys.settrace()? Anyway, it's a small detail, but...
If there is no acceptable way to emit only a type warning, static type checking really isn't feasable. In which case, the only proposed "improvement" is explicit type signatures on functions, which can only be checked at runtime. In that case, you might as well provide the entire DbC framework (including interfaces) and satisfy everyone.