Static typing [was Re: Python and the need for speed]

Steve D'Aprano steve+python at
Mon Apr 17 06:52:43 EDT 2017

On Sun, 16 Apr 2017 02:27 pm, Steve D'Aprano wrote:

> Are you aware that optional static typing CANNOT be used for optimization?

I think I've over-stated that. Considerably. In other words, I was wrong.

As Steve Yegge points out, dynamic languages like Smalltalk and Lisp were,
back in the 1980s, heavily optimized and were competitive with
statically-typed languages like C:

While this is true:

> Since it is *optional*, it is only a hint, not a fact. You can tell the
> compiler that you believe that n will be an int, but it's not guaranteed.
> As the Dude says, the type hint is
>     that's, like, only your opinion man
> and the compiler cannot trust it. It must still guard the operation with a
> runtime check that n actually is an int, 

The conclusion that I drew:

> and so you lose most or all of 
> the benefit of telling the compiler that it's an int. 

is not necessarily the case. If you're doing lots of little operations on
disparate variables, with lots and lots of guard checks and not much
optimized code, it will go badly for you, but on the other hand for big
loops with only a few up-front checks and predictable types, there may be
opportunities for optimization.

Honestly, I'm not quite sure what I was thinking: that sort of "optimized
code with a guard" is exactly what Psycho does, and what FATPython is
hoping to bring to CPython some day.

At the present time, the state of the art of gradual typing is still keeping
the emphasis on optional static typing for *correctness*, not optimization:

but research does continue into using gradual typing for optimizations:

> Python's gradual typing is not about optimization, it is about testing
> program correctness and helping to find bugs at compile time*. 

That's the motivation for MyPy.

“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

More information about the Python-list mailing list