470 points · by tabbott · 10y ago · 221 comments
One comment to the article author: Tell people how to install mypy. I started by trying 'pip install mypy', then wondered why I didn't end up with a mypy executable (you need pip3 install mypy-lang, mypy is an unrelated package).
Consider the first example,
def sum_and_stringify(nums: List[int]) -> str:
return str(sum(nums))
The type here is way more specific than it needs to be. Not only will this work on any sequence type (anything that supports __iter__), the element type only needs to support __add__ and __radd__ (to work against the implicit seed value of sum).I really feel like in order to get the best of duck typing, you need a good syntax for describing types by usage, not by explicit name. Please let me know if I'm missing something, and this is actually more expressive than the documentation suggests.
The concept of 'type' is overloaded with too many meanings these days. It started out as a what-storage-to-allocate and which-instruction-to-generate (int v float) concept (FORTRAN I, variables starting with I..N are ints, others real). Deep class hierarchies muddied the waters by overlaying the idea of whether or not a class implements a particular property or method, and how to locate the property or method that you want.
Python shows us that types and protocols/interfaces are two very different thing. In Python, asking 'isinstance()' is usually a bad idea unless you are doing something very low level, low level as in next stop is a C extension. The missing predicate in Python is 'hasprotocol()'. Abstract base classes can be used to accomplish that: isinstance(foo, SomeABC), but I think the intent could be more transparent with different syntax.
I like the idea of a hasprotocol or supportsprotocol predicate, certainly over usage of isinstance, since one of the beauties of duck typing is that it works without requiring the type hierarchy. The tricky part will be in allowing you to define your own protocols, like "has these attributes/methods". An example would be the difference (or lack thereof) between classes and namedtuples.
* https://docs.python.org/3.4/library/collections.abc.html * https://hg.python.org/cpython/file/3.4/Lib/_collections_abc....
Interesting perspective. This would seem to be pretty well described by parametric polymorphism with constraints (Haskell-style polymorphism with typeclasses). In that context, too, we are often well served staying as generic as possible, and asking at runtime about the type of something is a bit of a code smell (and only possible where you have a Typeable constraint available).
Or: Maybe haskelltyping
> mypy considers an int object to be valid whenever a float object is expected.
> Use Iterable for generic iterables (anything usable in `for`)
Thus you should be able to get a more broadly correct (though still not 100% if you have your own types implementing __add__ and __radd__) like this:
from typing import Iterator
def sum_and_stringify(nums: Iterator[float]) -> str:
return str(sum(nums))
It also looks like implementing an abstract base class SupportsSum (to check for __add__ and __radd__) may not take a whole lot of work, see `SupportsInt`: https://github.com/python/mypy/blob/d7f6ea617317103534d86686...http://mypy.readthedocs.io/en/latest/class_basics.html?highl...
Not sure if this is of interest to you, but the Nim[1] programming language offers a feature that allows you to do exactly what you described. It is called concepts and is documented here: http://nim-lang.org/docs/manual.html#generics-concepts
As a bonus, Nim is also quite Python-like.
# optionally: Number = Union[int, float, complex]
def sum_and_stringify(nums: Iterable[Number]) -> str:
return str(sum(nums))
also works. Except no one knows what the Number abstract base class is (or even the Iterable abstract base class for that matter)mypy will then tell you if you used your documented code wrong, according to your documentation
also sum excludes summing of strings if I remember correctly, so its any object that has an __add__ and __radd__ and isn't a string or subclass of string. which is just a bit insane to try and express on one line!
def sum(iterable):
r = 0
for v in iterable:
r += v
return v
it always starts with an integer, and since int.__add__(str) returns NotImplemented it tries str.__radd__(int) instead, which raises an AttributeError because str has no method __radd__, so no summing of strings and integers. >>> sum(['hello', ' world'], '')
TypeError: sum() can't sum strings [use ''.join(seq) instead]
But this is done explicitly against strings. They would _just work_ if not for this restriction, because based on usage they should work.On the point of documentation, this is potentially a fair point if you consider that you probably wrote this function for a particular usage and you know at design time that you're really only ever going to give it a list of ints (if you strip the types away, the parameter is still called nums which suggests that's what was really intended). In reality, the function is actually much more powerful than that, and if included in a library, many people could use it for many more things than just that.
I think all this says is that design and documentation considerations for functions in distributed libraries may be different than those for functions used locally. Something I certainly agree with, but not really a criticism of the parent point.
Correct and concise documentation is incredibly valuable.
For documentation to stay correct, it must be checked and updated as situations change. Types and assertions can both play this role. Tests can play this role.
Names also play this role - they are not mechanically checked, but "is my use here consistent with the name" is a check any programmer is applying as they work. This actually argues a bit against renaming refactor tools - if I am changing a name, I should be making sure that it squares with existing uses. From this perspective, checking of function parameter namess is weaker than checking of function names, since the names of the parameters typically do not appear at the use site - very different than the assignment of other variables.
Which is for practical purposes impossible.
Semantically, the presence of __add__ and __radd__ is a minimum, not sufficient.
Edit to add: To be clear, sure the result of calling this on any arbitrary sequence of addables might be semantically nonsense, but that's not the purpose of a type checker. It's only to verify type safety, i.e. you won't get runtime type errors if you give me at least this kind of thing.
A more constrained type throws away "the advantages of Python's duck-typing", but it also throws away disadvantages, and that can be precisely what you want.
We either disagree about the purpose of a type checker, or we disagree about what can constitute a "runtime type error". If a type checker can catch inconsistencies that would lead to my returning "semantic nonsense", at low enough cost, I absolutely want it to. Obviously it won't be able to catch all such inconsistencies in all cases.
Of course type checking can catch some problems. The more extremist elements of the static types proponents seldom seem to ask the cost of adding types, and making some otherwise generic/overloaded operations harder to implement (e.g. - excess clutter in some "wordy" type systems, particularly in the C lineage where declared identifier names follow the other verbiage). We need more tools that allow us to easily nail down fixed interfaces to avoid errors, but still allow flexible / dynamic / metaprogramming type code when needed, without having to jump through hoops in either case.
Don't be a static typing extremist! (or throw the baby out with the bath-water, either, I guess)
Note that I am referring to type systems with succinct syntax, type inference, structural typing and ADTs.
Here is a little list of drawbacks of static type systems with features like you describe (parametric types, ADTs...): Type dependency hell (banana, monkey, jungle, etc), having to fight/convince the type inferencer to accept any but the simplest things, having to type many things twice.
Looking at Haskell, "almost everything is inferred" is a lie in my experience. You are encouraged to write code using higher-order and highly parametric functions. If you do, the error messages you'll get if you don't annotate are plain sick. Another problem is that the type system provides no convenient escape hatches, while it's not powerful enough for typical programs. Many "successful" example designs I've seen are either _really_ simplistic (to the point where it's obvious that the better design wasn't chosen simply because the type system makes it really inconvenient), or have some _really_ terrible internals hacking in it (which might be the largest part, be impossible to understand by most developers, and break with the next compiler version).
Looking at C++, a practical example is vector. It's a useful tool (automatic memory management), and very likely to be all over in your function signatures. This is very bad in terms of modularity / reusability, because your functions are not defined using reasonably general types (pointers to arrays).
Many of these very real pains just aren't there with Python code, which has better modularity at the cost of being a little sloppier.
These days I look at static types mostly as tools for generating fast machine code (I doubt that much more than C types is needed here) and as tools for enabling nice syntax (OOP protocols like in Python can do that too, but they are very dirty). These things however are only needed at the very optimized parts of your average project.
So I think a good way in many cases is to go the Python route, and check types dynamically at strategic points to assert value integrity and enable transition to highly optimized (with static types) routines.
Either that, or you might not work on toy projects.
That's why you define your functions as taking generic Iterators instead, which generalize pointers to arrays. Or, in more modern style, generic containers.
You can wrap that in a type erasure layer (lookup any_iterator) if you want separate compilation.
What do you mean by "tables"? I think of a database table of rows/columns, or a matrix.
Keep in mind, static types can also help performance, tooling (refactoring, cross-referencing, etc) and human understanding.
This is not an argument for or against static types; it is simply a longer list of what they can be useful for in the many situations.
I just don't want to be forced into a jail cell 100% of the time. I want an escape hatch to do the needful once in a while to do something that the language designer never planned for.
You can also do full Python-style "duck typing" statically. It's called structural typing, with native support from languages like typescript, purescript, etc. It's used a lot in web dev because it works well with Javascript's object model.
This is true for the JVM definition of 'generics', but it doesn't mean that arbitrary operations on a collection of types can be easily expressed with a given (static) type system. Run time type information + a dynamic type can ameliorate some of this, but that's shoehorning optional types into a static type system, and I don't think that's quite what you meant.
Think about a generic operation to diff two data structures: you need access to the members of the struct in a generic way. I don't think this is easily solved with static types.
Java generics seem easy enough to instantiate and use, but the mess when you implement one really discourages people from trying, usually. And if you do, the result is often a poster child for FUGLY code. Try declaring a java 8 lambda parameter that works with collections some time, and using that in a few places - serious COBOL-fingers and eye-burn time. Even a Pascal style "type" or C style "typedef" mechanism would have greatly reduced clutter when trying to create code that implements (java) generic operations.
Die, Java, die :-)
Using an explicit map for dynamic attributes at least makes you aware what is guaranteed and what is optional.
This removes much of the neat magic that such a dynamic approach affords to languages like Ruby, JavaScript, and, to a lesser extent, Python.
It feels like type inference meets duck typing, but that's a good thing.
C# has the dynamic keyword (not to be confused with type inference via the var keyword), which basically allows to break out to dynamic typing. I find this to be significantly saner than the other way around.
IMO writing a type annotation, or knowing whether a type is an int or a string, is the of minimal help in pushing errors into the type system. A good type system you don't even have to write the type of things, it's inferred.
Better 'statically typed' languages allow you to push more errors into the type system and give you tools for creating stronger abstractions.
Even if they don't do it very often, even if the IDE infers properties most of the time anyway, even if there's less code to have to be refactored, and most of the refactoring that could be automated is still automated.
I would rather use types most of the time for clarity and to help the compiler / editor help me, just not always.
:-)
I like the idea of a hybrid type system where statically typed and dynamically typed parts coexist, OTOH, I can imagine it being difficult to implement.
[Source: I'm a mypy core developer.]
However:
s/was/is/g
s/could/can/g
Premature burial is a little bit scary, I take it you are doing this because Halloween is near.That discussion was an eye-opener for me regarding type systems; to this day, I cringe when somebody calls, e.g. Python or Javascript a "typeless" languange.
There is some controversy over the strong/weak terminology, IMO mostly because almost no language is clearly strong or weak based on the definitions generally used[2]. I find it useful to think about whether things are done implicity, or whether you need to specifically convert types. Perl will happily add "1" and "1" to get 2, because the + operator forces it to be interpreted as a numeric type. Python will not, and expects you to convert to a numeric type first. Of course, exceptions to the rule abound.
1: http://stackoverflow.com/questions/2351190/static-dynamic-vs...
There is no generally agreed upon definition of what the distinction means.
Out of curiosity: if I'm not mistaken, this was an implementation detail of LISP machines [1], and allowed bytecode-level optimizations.
If you take that seriously, compilers can't use type information to optimize. It feels like Von Rossum is making life hard for the PyPy compiler project again. If they had hard type information, they could do serious optimizations. Guido's CPython still uses a CObject for everything internally, so it doesn't benefit much from this.
The direction that everybody else seems to be taking is that function parameters, structure fields, and globals are typed, but local types are inferred as much as possible. C++ (with "auto"), Go, and Rust all take that route. Type information on function parameters and structure fields is an important item of documentation; if the language doesn't support that, you need to put it in separate documentation or comments. But writing elaborate type declarations for local variables is no fun, and the compiler can usually infer that info anyway.
1) Not type checking at runtime is exactly what people mean by static typing, because the definition of static typing means the checks are done before execution.
2) This does not make it harder to optimize, on the contrary if they generated type assertions it would considerable slow things down on the boundary of typed and untyped code.
3) C++, Go, Rust, Haskell they are fully statically typed, the only difference is they support varying levels type-inference which means you don't need to "type out the type" but it's really orthogonal to the whole optional/static/dynamic typing issue.
"Type inference refers to the automatic deduction of the data type of an expression in a programming language."
https://en.wikipedia.org/wiki/Type_inference
Which you'll notice C++ and Go, are listed as languages with type inference.
But you're right that they don't have as nearly as strong type inference as rust, which doesn't have as strong as haskell etc.
(When you have a real type inference engine, you spend a lot of time trying to figure out what it did, or why it didn't do something.)
Mypy is not about optimising anything, it's about static correctness guarantees. If you're developing PyPy, type hints shouldn't be making your life any better or worse.
Lastly, the 'direction' you describe that everyone else seems to be taking, is the exact same direction mypy has taken. Type annotations are only required at the method/function level.
My_dict: defaultdict[int, List[int]] = defaultdict(int)I've run into that with functions that take NumPy arrays. You can pass a Python array, but "+" behaves very differently. For a NumPy array, it's element by element addition. For a Python array, it's concatenation. You want to catch that.
Or perhaps, he realizes that to require these typechecks at runtime would either
- require a massive rewrite of the CPython interpreter
- cause a performance penalty in code that is statically typed (there are pure python libraries that allow this, and yes your code runs slower)
Further, it offers a relatively narrow amount of help to pypy, which has already come out and said that they have no interest in using annotations for efficiency gains, because they're a jit and they don't need them.
Von Rossum on PyPy (2016): "Otherwise, there are specialized versions of Python like PyPy that are still around."
[1] https://bitbucket.org/pypy/pypy/src/default/rpython/translat...
I think that's a fair trade off, and easily doable. Those who want it and respect it get the speedup, those who don't don't lose anything.
If you have to double check types at runtime, you've already lost.
Now if it isn't correct, you'll probably get a segfault or some nasty error and it'll blow up.
Woah! Excellent news. Really cool that they found a way to use this opportunity to bolster Python 3 migration.
Or does type documentation not matter that much, once it's being enforced by a tool?
Improves IDE integration, especially IntelliJ PyCharm's jump-to-source
- the official docs are useless, return types are often not documented (wtf ?) and docs aren't structured and clean. Python documentation is a giant mess.
- mypy is a god sent I used it from day one to document my Python code, but it needs better integration with python doc tools, 3rd party linters and co.
I'm ok with optional type checking. A team can make it mandatory during continuous integration while not breaking legacy code, but I hope mypy will be directly integrated to Python in the future and not a 3rd party tool.
Instead of a list of possible returns with some kind of prototypes you may be left with description: "The returned object is always a file-like object whose file attribute is the underlying true file object.".
See for example documentation for tempfile.NamedTemporaryFile [1]. This time possible returns are not in the separate paragraph as is in many other cases. You can't click anything expect TemporaryFile(), so you have to search for proper reference. The information is there, but instead of quick glance you have to parse and search more text.
Hoo boy. That's not a good thing. A consistent type system doesn't have "false positives". Reading between the lines, this means "the type checker is incomplete and allows incorrect types."
What is the story here with constraints, polymorphism, etc?
Currently you need to import things like Callable, Tuple and these don't exist in Python2. It is especially odd since I am using MyPy comment syntax, so MyPy needs import statements even when all types are inside comments.
I like the way Haskell puts type information above the definition.
This is a direct backport of the same `typing` module that's in the stdlib starting in Python 3.5.
(I'm one of the mypy core developers and work at Dropbox. We're using PEP 484 and mypy on a lot of Python 2 code!)
def f() -> "Bar": ...
instead of def f() -> Bar: ...
(This is normally used for forward references.) This makes it slightly less nice, but not a terrible workaround overall.Javascript is the bash of the internet. It's not that great but it does have a "killerapp".
http://groovy-lang.org/releasenotes/groovy-2.0.html
[2] https://github.com/shedskin/shedskin
Citing some Groovy 2.x Release Notes to prove a claim of "stability" for Groovy is like quoting an advertisement for Parmolux washing powder to prove its "effectiveness" at washing out dirt.
Not many developers bother with Groovy's static compilation annotations. It's used mainly as a scripting language for testing Java classes, gluing together Java programs, as a build DSL in Gradle, and scripting in Grails. When static annotations are used, their use is typically small-scale.
The primary Python execution environment is commonly referred to as CPython, as it is written in C. Other major implementations use Java (Jython [Jython]), C# (IronPython [IronPython]) and Python itself (PyPy [PyPy]). Written in C, CPython has been conducive to wrapping many external libraries that interface through the C language. It has, however, remained non trivial to write the necessary glue code in C, especially for programmers who are more fluent in a high-level language like Python than in a close-to-the-metal language like C.
Originally based on the well-known Pyrex [Pyrex], the Cython project has approached this problem by means of a source code compiler that translates Python code to equivalent C code. This code is executed within the CPython runtime environment, but at the speed of compiled C and with the ability to call directly into C libraries. At the same time, it keeps the original interface of the Python source code, which makes it directly usable from Python code. These two-fold characteristics enable Cython’s two major use cases: extending the CPython interpreter with fast binary modules, and interfacing Python code with external C libraries.
While Cython can compile (most) regular Python code, the generated C code usually gains major (and sometime impressive) speed improvements from optional static type declarations for both Python and C types. These allow Cython to assign C semantics to parts of the code, and to translate them into very efficient C code. Type declarations can therefore be used for two purposes: for moving code sections from dynamic Python semantics into static-and-fast C semantics, but also for directly manipulating types defined in external libraries. Cython thus merges the two worlds into a very broadly applicable programming language.
def primes(int kmax):
cdef int n, k, i
cdef int p[1000]
result = []
if kmax > 1000:
kmax = 1000
k = 0
n = 2
while k < kmax:
i = 0
while i < k and n % p[i] != 0:
i = i + 1
if i == k:
p[k] = n
k = k + 1
result.append(n)
n = n + 1
return result
http://cython.readthedocs.io/en/latest/src/tutorial/cython_t...I know some may disagree but I have found runtime reification of types fairly useful in the Java world (partly because Java does not have good code generators like OCaml/Haskell and partly because Java is not that expressive).
https://jugad2.blogspot.in/2012/12/mypy-python-variant-with-...
but had not tracked it much after that. Must check it out again.
The good thing about types is not that you can just annotate (or not with good inference not) and validate that some type is what you expect it to be. It's that with a proper type system you can develop better abstractions.
It's amazing. Zulip is Slack done right. Their threading/light-weight topic approach is second to none.
Another example of this is most of the prismatic/schema-esque frameworks for python to do validation on datastructures. Instead of saying foo must be { "name": "String" } (where there is a framework-specific meaning behind the literal word "String") we should take advantage of the built-in types and say {"name": basestring}.
End rant.
python3 type_annotations.py
def sum_and_stringify(nums: List[int]) -> str:
NameError: name 'List' is not definedEDIT: Solved: Either just list or List[int] with import:
from typing import List
Thanks for all the help guys! By the way I took the example from the mypy page. A classical case of 'critical line missing from example code' (as perfectioned by Bjarne Stroustrup back when)
At least this works: def sum_and_stringify(nums: list) -> str:
How I found it: quick google search for "mypy validate list"
sum_and_stringify(nums: List[int]) -> str:
This looks so bad. I think Python is making a big mistake with this.The commented version is much more acceptable.
----
It should work with the Python 3 syntax if you quote your type annotation. I.e.
def f() -> "Bar": ...
instead of def f() -> Bar: ...
---Yeah, you need to write `from typing import List` to get the generic List class that you can parameterize with an item type. As you pointed out, you can use the builtin lowercase-l list without importing anything, but that doesn't allow you to specify the item type.
---
imo, this is brutal. I'll just wait and see whether I'm proven right or wrong, but the extremely poor aesthetics of the whole thing bode badly.
You listed 4 specific languages, but the following things are each inconvenient in them:
- C: it's inconvenient to implement a quick prototype
- Ocaml: it's inconvenient that the stdlib is so small
- Go: it's inconvenient for scientific/numerical code
- TypeScript: it's inconvenient to run server-side
Obviously you can do everything in any language (Turing, blabla), but the question is, how much effort (time) does it cost.Python rocks in all of them (edit: the big exception being frontend webdev), in particular for quick prototyping. I think mypy is an exceptional and fine contribution to the eco-system and I really appreciate their effort.
How much I would like Webassembly to be ready to open the gates to other languages on the frontend land. Anyone here has more information about webassembly / python on the browser? I would love to know what is the current state of the art of running python on the browser and contribute to make the dream come true.
I have on my radar Brython [0], py.js [1](seems to be abandoned) and pypy.js [2]
[0] http://www.brython.info/ [1] http://pyjs.org/ [2] http://pypyjs.org/
I don't know what "strictly typed Python" is, but the type checking discussed in this post is 1) completely optional and 2) static. You don't have to do it if you don't want to, and even if you do do it, it doesn't affect in any way Python's runtime behavior or flexibility. You can have a codebase that works fine yet at the same time fails mypy's checks.
Also, no, we are not moving towards "strictly typed Python", even if that were a thing. PEP 484, which laid out the standard type hints, included this line in bold under "Non-goals" [0]:
> It should also be emphasized that Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention.
I used typing with PyCharm for one of my project and it helped me to find several bugs.