128 points · by zdw · 5y ago · 124 comments
The authors don't seem to ever discuss the fact that mypy version changes frequently make previously-passing code fail type checks.
I don't think I have ever upgraded mypy and not found new errors. Usually they're correct, sometimes incorrect, but it's a fact of being a mypy user. Between mypy itself and typeshed changes, most mypy upgrades are going to involve corresponding code changes. The larger your code base and the more complicated your types are, the worse it'll be, but it's basically an ever-present issue for any program interesting enough to really benefit from a type checker.
How many of those repositories were "type-correct" but only on particular versions of mypy? I bet it's a lot!
But the big culprit is typeshed. Something will get new/fixed annotations and suddenly you aren't handling all possible return types in your callers, or whatever.
I can't show any of my professional work (no publicly available src) but this side project of mine is locked to 0.790 until I can find time to sort the issues: https://github.com/calpaterson/quarchive/tree/master/src/ser...
It's hard to classify anything as a "false negative" with mypy since it is very liberal (often unexpectedly so, which I think is one of the sharp edges of gradual typing).
I think mypy has some problems, but this isn't one of the bigger ones for me.
Though I will say, while most have been fixable in a few minutes, some have been a real chore to fix. Sometimes an innocuous looking error balloons into several hours of reconciling obscure type system behavior errors once you start fixing it. Regardless, it's a small price to pay for proper type checking in Python. I've more than made up the lost time in detecting bugs before they ship.
You can argue that when it removes features it provides a replacement (sometimes), but that does not change the fact that if you have any reasonably large project (>1 million LOC), every standard upgrade will break your app.
One of the main reasons we write all new code in Rust and are migrating the C++ code base step by step to Rust is because Rust offers infinitely better backward compatiblity guarantees than C++.
Rust never ever breaks your code, and you can opt-in to newer Rust editions for new code only, and these are ABI compatible with Rust code written using older editions.
MSVC: https://github.com/onqtam/doctest/issues/183
GCC:
- https://invent.kde.org/qt/qt/qtbase/-/commit/8252ef5fc6d0430...
- https://invent.kde.org/qt/qt/qtbase/-/commit/cb2da673f53815a...
One thing I didn't see mentioned that is a particularly annoying false positive in mypy is the enforcement of Liskov Substitution for equality checks. All types have the common bottom type of object and object itself defines the __eq__ magic method as accepting any other object, which means all custom Python classes that want to define an equality check have to either define the '==' operator as valid accepting anything as a second operand, or tell mypy to ignore the error, which is the obviously saner thing to do since you want a type error, not a return of False, when you check equality against a completely unrelated type. Unfortunately, mypy provides no way to give you that statically.
I'm glad they mentioned the default parameter None to avoid the classic footgun of empty collections, though. That has to be the single most annoying false positive, when you declare a parameter as Optional and the type checker then complains it was set to None in the parameter definition but later set to an actual value, which you have to do because of the totally insane and unintuitive fact that all invocations of a Python function share the same parameter, so filling in the empty list with something else upon calling it means everything else that calls it now gets the changed default value instead of the empty list.
This is probably the single greatest rookie mistake made in Python because of how unexpected it is if you don't deeply understand the object model, but doing the literally recommended by the book solution to get around it results in the official type checker endorsed by Guido himself to report a type error.
def f(l: List[int]=cast(Any, None)) -> int:
if l is None:
l = []
...
f()
Using casts is useful for all sorts of things like this when sentinel values/objects are involved. People often feel it's somehow 'wrong', but it's fine to trick the type checker as long as it's localized to neighbouring lines of code :)What? No I don't?
foo = if x: Foo else 1
foo == 1 # why would I want this to throw? I just want False!
Disclaimer that I haven't done much Python recently (or Java, ever – I wonder if raise-on-== is a java-ism) class MyClass:
def __eq__(self, other):
if not isinstance(other, MyClass):
return NotImplemented
else:
# whatever your comparison is
When NotImplemented is returned, there is a fallback sequence described in https://docs.python.org/3/library/numbers.html#implementing-... - where basically, in the expression `A == B`, if `A.__eq__(B)` returns NotImplemented, then `B.__eq__(A)` is checked as well (falling back to an `is` identity comparison if both return NotImplemented).This is neat because it allows you to define a class B that can compare equal to an existing class A with the expression A == B, even though class A has no knowledge of B.
In your example, `foo` could be marked (in mypy) a `Union[Foo, int]`, which would be a reasonable value to compare against an `int` and not a type error.
For an example, consider `np.eye(4) == 1`. In this, you're comparing a doubly nested array of floats with a scalar int, but the operation is well defined (vectorized equality comparison).
And yes, it should be feasible to typecheck that operation.
Well, actually as long as they implement the right dundermethods, they can totally be.
You're saying is that an 8-bit number can never be equal to a 16-bit number, or a 32-bit number, or a...
I hope you agree that's ridiculous.
There are two forms of equality in Java:
- 'x == y' is an identity check, like 'x is y' in Python (are x and y referencing the same memory?). These must be of the same type, or else it won't compile.
- 'x.equals(y)' is an overridable method, like 'x == y' in Python. Its argument is of type 'Object', so it will accept anything.
I don't do much Java these days, but I do write a lot of Scala (which runs on the JVM). One of the first things I do in a Scala project is load the 'cats' package so I can use 'x.eqv(y)' which refuses to compile if x and y are of incompatible types. This problem also propagates up through different APIs, e.g. 'x.contains(y)' checks whether y appears in the collection x (which could be a list, hashmap, etc.); this doesn't check the types, and I've ended up with bugs that would have been caught if it were stricter. I now prefer to define a safer alternative 'x.has(y)' which uses 'x.exists(z => z.eqv(y))'.
I think it does make sense if you consider the function signature an expression scoped one level above the function definition. I agree it's initially not intuitive, and it's tripped me up a few times before as a beginner, like probably most other beginners.
As a more experienced Python developer, I think I'd actually now find it unintuitive if they changed it, due to everything I've internalized about Python scope, values, assignment, expressions, etc. Same for always requiring "self" as the first method argument. Overall, I'd prefer the changed versions, but I think they (or someone else) would basically need to make a whole new spiritual successor language.
What does take a long time is learning about it all. There's the docs, then PEP 484, then at least eight other related PEPs of various impact. It would be a good topic for a small book / website / course, except things change kinda fast.
I do think it could be a hack for a new dev to establish credibility. Spend a few months type hinting code and fixing bugs in popular open source repos. You'll learn way more about real software engineering than following another tutorial. If someone wants to do that and wants some mentoring, hit me up at my last name at gmail.
That said using type annotations made me realize I want to be fluent in a language with a strong static type system (huge productiveness booster imo), so I'm currently studying Typescript and nim.
It is part of mypy, and it compiles type-valid python files to cpython binary extensions, and takes advantage of a lot of shortcuts available to cut execution time. It is still a bit early to advocate for its use everywhere, and has it drawbacks (extensions compiled with mypyc will also typecheck the inputs and outputs of the module at runtime, which is great for improving code quality and validity of the annotations, but also means you may get TypeErrors in production if you hit a bad edge case).
If there is no shortcut it will fallback to normal, slow, python performance, with some smallish benefits (e.g. vtables for attribute lookups, no parsing time, etc).
How does it compare to Nuitka? https://nuitka.net
For comparison, Racket has gradual typing which gives a speed boost when everything is typed, but can end up much slower if anything remains untyped, e.g. see figure 3 in http://www.ccis.northeastern.edu/home/types/publications/gra...
Python would probably be even worse, since it's "more dynamic" than Racket; e.g. there are many hooks that can run arbitrary code (like dunder methods), and there's little encapsulation so values may get swapped out via monkey-patching at any time.
Not trying to start language wars here, of course, I'm just interested because I find Nim one of those languages that I'd like to try but don't have a project/use case to try on.
Also useful for autocomplete.
For me, most of the value of typing is at the function level: what does this function accept as input and what does it produce as output?
Also mypy gets in the way of using loop constructs, as the iterating variables have to be predeclared with typing before the loop, breaking encapsulation.
output = []
for x in range(1):
output.append(x)
reveal_type(output)
# note: Revealed type is 'builtins.list[builtins.int*]' x: MyType
for x in y:
...
for x to be annotated properly.Does Pyright behave like MyPy or PyType? Or neither?
Also did Python really create a type annotation system without specifying the semantics of how it is supposed to work? That's crazy.
If the type checkers disagree on stuff defined in pep 484 that’s a bug to report. Beyond that they can vary but feel mostly similar.
Splitting out the mistake checking and the data specification aspects of types would probably make pieces more portable across different languages
- Static + Weak = C
- Static + Strong = Haskell
- Dynamic + Strong = Python
- Dynamic + Weak = JS
and, in particular, explicit vs. implicit type casts of those objects.
Examples:
Python: strong, dynamic
PHP: weak, dynamic
C: weak, static
Haskell: strong, static
I expect that everybody doing this job has a CS or equivalent degree and knows the difference between strong / weak and static / dynamic typing. Reading other comments here demonstrates this is not the case. This is not a bad thing (luckily we only need a screen and a keyboard) but hopefully they'll have learned something new today.
Btw, there is a lot I don't know despite my degree. No hard feelings.
def comparativeInsult(a,b):
if b>a:
return "try again"
if a>b:
return a/b
else:
return None
The type is, for all practical purposes, a part of the value of a Python object.> "Dynamic typing" The belief that you can't explain to a computer why your code works, but you can keep track of it all in your head.
— Chris Martin (https://chris-martin.org/2015/dynamic-typing)
Here's my response to that quote:
"Static typing": The belief that if your code type-checks correctly, it will do exactly what you intended. (A variant of the belief that if your code compiles correctly, it will do exactly what you intended.)
Of course, taken literally, that's unfair, but so is the quote you gave. Everything you add to your code has a cost. Time you spend writing type specifications is time you're not spending doing something else that might add more value. Sometimes writing type specifications is the best use you can make of that time; sometimes it isn't. Python at least gives you both options: use type annotations if you want, but you don't have to if you don't want to.
No-one claims that typechecking solves 100% of problems. But it has a higher cost-benefit than anything else that's been tried.
> Time you spend writing type specifications is time you're not spending doing something else that might add more value.
So is time you spend thinking about the behaviour of the code in your head - the main difference is that it's slower and more error-prone.
Occasionally you really can do the calculation about what kinds of expressions are valid in which places better than the computer. But that's a rare case that gets rarer every day.
> Python at least gives you both options: use type annotations if you want, but you don't have to if you don't want to.
Not really: your code will almost always be silently unsound. E.g. libraries you're using will usually have incorrect type annotations (because their type annotations aren't checked, and the checker is unsound even if they were).
In contrast if you use say Haskell you genuinely do have both options: you can write code and have it be safely typed, or you can call unsafeCoerce at any point where you don't want typechecking to happen.
I'm very enthusiastic about static types with global type inference, where I don't have to write a single type annotation if I don't want to. My enthusiasm degrades pretty quickly the more annotations I have to manually clutter my code.
I see way too many code bases that test things that are easy and xfail things that are hard because it turns out that you can’t just test your way to a complex product, but you sure can make yourself feel good by testing the fact that a dict acts like a dict.
I would certainly argue that anyone who writes a library, whose public API will be consumed by hundreds or thousands of people, should always include type annotations.
After working in a TypeScript codebase for so long, it's jarring to return to Python or even vanilla JavaScript where I no longer have breadcrumbs to help me keep track of how the code is organized.
Python's type annotations leave something to be desired, in terms of how easy they are to include in code and how well the tooling supports them. I'd almost rather see something like "Typethon" with better syntax+soundness that compiles-to-Python.
Types are an optional tool, sure, but they're one of the most valuable tools we have to catch (not eliminate entirely) bugs and hasten development (without introducing errors).
With a little care and a sufficiently strong type system it’s surprising how often this is actually true.
> Dynamically typed languages are actually statically typed with precisely one type: hash table.
Because by this definition makes C++ and Java look dynamic with vtables.