December 21st, 2014
(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: firstname.lastname@example.org
When I wrote How ignorant am I, and how do I formally specify that in my code? I said:
For decades, computer programmers have argued with each other over the issue of strict data-type enforcement, versus dynamic data-type unenforcement. And after 16 years of computer programming, I have come down firmly in the middle: I like optional typing.
Clojure allows me to work dynamically, but to type hint when I want to, so I can get the performance benefits of type hinting. There is also the new Typed Clojure that will let the compiler give me a warning when my types are wrong.
Apparently Python 3.5 is headed in this direction. Guido van Rossum points to Jeremy Siek’s blog post What is Gradual Typing where he says:
Gradual typing is a type system I developed with Walid Taha in 2006 that allows parts of a program to be dynamically typed and other parts to be statically typed. The programmer controls which parts are which by either leaving out type annotations or by adding them in. This article gives a gentle introduction to gradual typing.
The following were our motivations for developing gradual typing:
Large software systems are often developed in multiple languages partly because dynamically typed languages are better for some tasks and statically typed languages are better for others. With a gradual type system, the programmer can choose between static and dynamic typing without having to switch to a different language and without having to deal with the pain of language interoperability. Hopefully this will increase programmer productivity.
Several languages already have optional type annotations, but
surprisingly, there had been little formal work on what a type
Say we have an Employee class, and a subclass Manager:
class Employee: …
class Manager(Employee): …
Let’s say variable e is declared with type Employee:
e = Employee() # type: Employee
Now it’s okay to assign a Manager instance to e (rule 1):
e = Manager()
It’s not okay to assign e.g. a string to e (since str is not consistent with Employee):
e = “hello” # Fails static check
However, suppose we have a variable whose type is Any:
a = some_func() # type: Any
Now it’s okay to assign a to e (rule 2):
e = a # OK
Of course it’s also okay to assign e to a (rule 3), but we didn’t need the concept of consistency for that:
a = e # OK