Typing system vs. Java

Jonathan Hogg jonathan at onegoodidea.com
Wed Aug 1 18:04:01 EDT 2001


In article <mailman.996592198.30711.python-list at python.org>,
 tanzer at swing.co.at (Christian Tanzer) wrote:

> Jonathan Hogg <jonathan at onegoodidea.com> wrote:
> 
> > I can though, think of plenty of places where strong static typing would 
> > defeat intentional exploitation of the dynamic typing. Maybe this is 
> > poor programming on my part, but I can't even think how one would type a 
> > function like say:
> > 
> >    def f(zs): return reduce( lambda x, y: x + y, zs )
> 
> Genericity (templates in C++) this is not a problem -- you get one
> instance of `f` for each type `zs` you happen to apply `f` to.
> 
> Disclaimer: C++ templates don't allow different return types for such
> functions, but that's a restriction of C++, not of genericity. IIRC,
> Ada generics can be generic in the return type, too.

Generics don't give meaningful types to functions. They simply delay the 
type-checking to the instantiator. Specialising a function each time it 
is used may be fine for native compilation, but not for type-checking or 
for Python VM compilation. I'd argue that even doing that, you couldn't 
come up with a workable type system for Python.

Exercise for the reader, think of types for the following:

   class BadBoy:
       def __radd__( self, other ):
           return "Oh yeah that's a %s!" % `other`

   pn = BadBoy()

   zs = [ 1.3, 0, 5, pn, " Hoo hah." ]

   heck = f(zs)  # using my previous f()

You can argue that this is a shitty piece of code (and I agree!), but it 
runs, and I don't want the compiler stopping me writing it.

The problem is that a dynamic language like Python creates types that 
are effectively as complex as the language itself. You end up concerning 
yourself so much with coming up with meaningful signatures, that you 
write the program in the type and have to execute it to see if it 
type-checks. That may be fine for proof systems like Alf, but not for 
Python.

As Michael Abbot observed:

> statically typed Python would need to be a 
> different language from standard Python

Now if you're just worried about speed and want to be give hints to the 
compiler so it can unbox types and optimise dispatch, then that's a 
whole different ball game. Do-able, but still tricky - as whenever it 
was unsure the unifier would have to insert box/unbox checks just in 
case and drop back to the standard dispatcher. You'd end up having to 
litter your code with type hints and assertions.

Someone argued that typing makes code more readable, I'd wager that if 
you took a standard Python program and annotated it to the level 
necessary to get sensible optimisation/checking out of it, a beginner 
would mistake it for perl ;)

Jonathan



More information about the Python-list mailing list