198 points · by Agathos · 6y ago · 126 comments
* Third party libraries are still not typed, which sucks
* Inference is weak. Sometimes an 'if' statement narrows accurately, sometimes it doesn't.
* Generics are extremely confusing, moreso than any other typed language I have used. Any Generics are even more confusing.
* Fundamentally, Python is structured such that the concept of interfaces are coupled tightly to implementation of classes, which is severely limiting. As an example, a module A can declare a class, a module B can declare an interface (Protocol), but module B can not implement that interface for A (without modifying A's code).
* Errors from mypy are still very very light. There are very few "Try XYZ to fix it", and it's just a single line of read text that amounts to an assertion.
* Still weak support for JSON (use Dict[str, Any])
* Slowly improving but still not amazing support for Self types
I could go on.
Mypy is awesome but it still feels very immature, and as it should since it's pre 1.0. It does not come close to matching the experience of other languages with static types.
* Regarding errors: there are few quite recent flags: ' --pretty', '-show-error-context' and '--show-error-codes', they make it a bit more pleasant. You can see me using them in this section: https://beepb00p.xyz/mypy-error-handling.html#container
Thank you for letting me know about those flags, I had not heard of them before!
Python 3.8 added TypedDict which finally helps this particular shortcoming.
Optional keys are also a nuisance.
if "optional_key" in my_dict:
do_something_with(my_dict["optional_key"])
Or: optional_value = my_dict.get("optional_key")
if optional_value:
do_something_with(optional value)
Works as expected. Nested optional keys can be a bit annoying, although: my_dict.get("optional_parent", {}).get("optional_child")
seems to work.It's nice to see strong progress in such important areas. My post is probably overly critical, but I write Python almost every day, and maintaining a highly-typed library can be demoralizing at times.
from mypy_extensions import TypedDict
https://github.com/python/mypy_extensionsWhile mypy and type hinting support in PyCharm and VSCode is great, it's not the seamless experience as with typed languages and the lack of (optional) runtime typing still allows all sorts of bad things to happen. A "safe" mode for Python, where typing and perhaps some other stuff is checked at run-time, might be an interesting advancement for those in the community building larger or mission-critical systems.
While static typing does catch code errors, in my experience they are mostly errors that would be caught somewhere else in the testing process. Memory safety issues are rarer, but also have a penchant for showing up unexpectedly and for crashing the entire system in unrecoverable ways.
Obviously, the best would be to have both kinds of safety, but people program safety critical systems in C++ all the time, and deal with the consequences. At least you can catch a TypeError in Python and handle it.
Catching TypeError in python and handling it is not a substitute for static typing.
You realize that many mission-critical workloads run on Python with great success, right?
Or rather, how would you define mission critical?
If you write str1 == str2, it compiles but probably does not do what you want (object identity vs string comparison).
(edit: to clarify, this does not mean Java is not a good language overall, every language has its own set of shortcomings and as someone points out in the replies, this behavior is consistent with everything else in the language)
Realising that type checking is a good thing, then bolting it on, I feel is a crappy solution, when you should just use something designed better from the start.
I completely disagree that there is a "productivity toll". If you dont know how to speak a language then obviously it seems difficult. I think you save time in the long run not dealing with all the type errors.
TypeScript's type system is far more powerful than Java's but I'm not sure that's a good thing. A lot of the concepts in TypeScript are necessary to paper over gratuitously dynamic APIs in JavaScript.
While Java certainly has warts in its type system (no generics over primitives, arrays), Java's type system straight-forward compared to TypeScript. TypeScript stuffs a staggering amount of functionality into the type system. To name a few of the more esoteric features: literal types, const assertions, asserts modifier for type predicates.
Have you written and deployed production code in the languages you mention above? Did you encounter a substantial number of type errors?
Is a '.close()' method being called twice a type error? It is in a language that can express states in the type system.
Is SQL injection a type error? It is when you use refined types in your sql library interface.
The vast, vast majority of errors I run into are errors that, with effort and the right type system, I could turn into type errors.
The point being that asking "would those be type errors?" is a really big question that is, when answered simply, "yes".
Pyflakes and unit tests will detect the great majority of potential errors. Mypy gets you closer to zero.
Regarding your criticism that `result.ok()` returns `None` if the value is not an `Ok` type: That's what `result.unwrap()` and `result.expect(msg)` are for :) (There's no unwrap_err and expect_err so far, but PRs are welcome.) The lib is strongly inspired by Rust (see https://doc.rust-lang.org/std/result/enum.Result.html), that's why `result.ok()` returns something option-ish.
I like your `isinstance` approach btw! Will have to think about it a bit more. Reminds me a bit of Typescript as well. Does mypy have type guards (https://www.typescriptlang.org/docs/handbook/advanced-types....)? Maybe that could be used to create helper functions that check for success/failure and which help mypy to derive the correct type.
not yet, maybe in the future. might be possible to emulate some use cases with Literal Types. tracking issue:
Now to sneak it in at work...
Also doing lots of messing with data for personal stuff (e.g. https://beepb00p.xyz/mypkg.html#examples). But yep, at least for me, the reality is if I need some quick yet useful code, Python happens to get me there very fast, just because of the sheer amount of code people already have written in Python.
Feel free to give it a shot! https://pypi.org/project/safetywrap/
I think naming the latter "Encode Typesystem" is misleading (and your question is an indication that I am right).
its a very common name.
T1 = TypeVar("T1")
T2 = TypeVar("T2")
GenericUnion = Union[T1, T2] def foo() -> OneOf[Bar, Baz]:
if blah():
return Bar()
return Baz()
def bar_to_blah(bar:Bar) -> Blah :
...
def baz_to_blah(baz:Baz) -> Blah :
...
one_of_bar_or_baz = foo()
blah = one_of_bar_or_baz.match(bar_to_blah, baz_to_blah)
but the critical thing is to get a type error if you add another case to foo's return type, or change the generics to different types.