by yuy910616 · 5y ago · 0 comments
and this one last year: https://www.youtube.com/watch?v=ST33zDM9vOE&t=68s
and finally this one in 2021: https://www.youtube.com/watch?v=Lj_9TyT3V98
I think I'll finally start using type checking - it really seems to just eliminate a whole class of potential bugs; a class that is often not tested at that.
As they are hints it means you can still pass in wrong values in some situations and what types check on one implementation may not type check with the other implementation. So the types are superficial only in Python.
The paper “Python 3 types in the wild” at https://news.ycombinator.com/item?id=26788177 is a good read. I enjoyed reading it and found it useful.
I’m a fan of types as the compiler tells me I made a mistake and blocks me making mistakes. You can use the type system to make certain errors unrepeatable (impossible to make). With that my preference is use a language where types are first class rather than a language trying to retrofit some loose form of type checking on top which is nothing more than linting.
Being a fan of strongly typed languages I was eager to use types in Python when I had to involuntarily use Python. After a few instances of putting in type hints and things type checking when they shouldn’t I mainly don’t bother with them now outside of data classes as they where not catching bugs I wanted so still getting runtime errors.
Four: Mypy, Pyre, Pyright and Pytype.
Python has several type checkers, as does Haskell, each with different soundness properties. What makes GHC's type checking more "true" than Mypy's or Pytype's or Pyright's?
GHC with its innumerable extensions and impenetrable (if well-defined) typing rules is and was always intended to be a testbed for wild type system ideas; that whatever it accepts became the received superset of standard Haskell (of which it is the only implementation) is in my opinion a failure of the Haskell community and the very thing that turned me away from Haskell after several years.
On the other hand, the only real description of what Mypy accepts is the source code of Mypy, and while many interesting programs that fall into that set also happen to be accepted by Pytype or whatever else, it’s not in any useful sense a bug if some are not. There’s also no practical way to tell if an arbitrary program is accepted except to try throwing it into the typechecker, because there is no human-adapted description of what constitutes being accepted.
None of which is to say that Mypy is not useful. It is useful, tremendously so. But as far as maturity of type systems in Haskell or SML goes, it’s not even in the same league. (So that this is not taken as academic elitism, neither are Scala, OCaml, or Typed Racket.)
GHC types are mathematically provable. Types are guaranteed to stay within your defnitions, so you can analyze the type graph without ever having to run the program.
You can certainly statically identify places where such changes are possible and the possible changes, in fact, Python static typecheckers do this.
> It's the Halting problem.
The Halting problem is a real thing, but you can simply bail out on any path that reaches a certain depth without resolution and fallback to the broadest possible type (failing narrower constraints) to avoid it.
Can you give an example of that? Mypy catches this:
def addsome(val: int) -> int:
val += 1.1 # tmp.py:2: error: Incompatible types in assignment (expression has type "float", variable has type "int")
return val
I'm sure there are cases where it doesn't notice, but afaik those are considered bugs. Doesn't Haskell have bugs?(There is also Liquid Haskell, but it doesn't check Haskell types, it checks Liquid Haskell types.)
Practically most large programs today can not pass maximal strictness settings as too many libraries lack type hints. But that's not a fundamental issue of python type system just a needed improvement of the ecosystem. Type hints are gradually growing and some major libraries have had noticeable improvements in the past year (numpy only started to have some types around 1.20).
Could you elaborate. When can you pass in wrong values?
The type checkers aren't always precisely the same (some do inference, mypy doesn't), but the cases where they disagree are usually because one is correct and one wants more information, not because you're able to do the wrong thing despite having annotations.
I use it whenever I can and it helped me find many bugs in the code (especially not checking if value is None through the Optional). It also makes refactoring your code in IDEs that understand types (like PyCharm) much much easier.
Haskell types aren't checked at runtime either, so that can't be it.
Python has runtime type checks that do happen at runtime, so maybe it's Haskell that doesn't have types.
I don’t have the specific example, it was something I observed not so long ago, said well that’s shit, fixed my code issue and moved on. Not being a huge fan of Python outside of small scripts and only using Python as told to use Python I took little interest in the detail as was a case of just get the job done and move on.
It’s been a while since I read the paper I shared but think that mentions it something similar if I remember correctly.
It's also been my experience (C(++), Kotlin, Swift) that as the complexity of typing increases, 10% of the time I spend servicing types accounts for 90% of the sites I need typing, and the other 90% of the time spent on types is me cursing at the compiler trying to make it accept the odd 10%.
An optional type annotation system allows ME to pick where I want that effort/payback balance to be at on a case by case basis.
The project has now scaled to multiple developers and many thousands of lines of code. If I compare my experiences this time around with past experiences in Python, I feel those early choices are paying big dividends in terms of code readability and correctness.
In particular:
The ergonomics of data classes is great (IMO). They avoid a lot of boiler plate, integrate well with type checking and auto completion, and provide clear context to anyone reading the code.
I’ve found Mypy a bit flaky (sometimes it misses errors it seemingly should catch) and some things that cannot be expressed in the type system to be pain points but overall having type annotations present and enforced helps document code, works well with IDE auto completion, and occasionally picks up errors that would have been otherwise missed.
In particular I’ve found it’s picked up a lot of errors around missing None checks (nullability). These seem to be particularly easy to miss in unit tests.
I’ve also found that PyCharm’s built in code code checking has often been able to pick up and highlight problems which it would have otherwise missed thanks to having type annotations. Having early feedback on problems is nice productivity boost.
One hint if you do use Mypy make sure to enable check-untuned-defs. You’ll get much better coverage.
I've posted a few reasons before. I think I've refined the list slightly since last time:
* People's first exposure to programming often came from using C++ or Java. An old version with really crappy type errors. Schools are often conservative about updating their tech stacks.
* Types are most useful when reading or changing code. New learners are mostly writing new code.
* Writing `Person person = new Person()` seems highly redundant. In the kinds of small programs you are writing as a newbie, you are likely to write a lot of this.
The reasons so far make types seem like overhead: you are having to do more work and getting little in return for doing so. The next two get a bit deeper.
* In the small codebases you'll have as a newbie[0] at disproportionate amount of the codebase is interacting with the outside world. The outside world is untyped. In both typed or dynamic languages, you have to shuttle this untyped data into your language's type system. But when there is a type error in this process, I find it is generally easier to debug in a dynamic language. That makes sense to me: they need to have good workflows for dealing with runtime type errors.
* Classes tend not to teach technique[1]. Students are expected to invent it on their own as they learn programming. As professionals, we often don't teach technique to each other either. If you invent techniques that leverage the strengths of types, then the appeal of types will seem pretty obvious. If you don't you may go years without before you are exposed to these techniques. If you invent techniques where static types get in the way, then you may find static types to be a severe hindrance to getting things done.
[0] I think this also applies a lot of the time when starting a new project.
[1] By technique I mean the steps you do to produce working code. This doesn't just include generating new code, but understanding existing code and debugging code.
I think if you're a SWE or has a CS education or worked with a compiled language before, you know exactly what kind of problem typing is solving. For me, I have to first discover the problem, slowly learn that there is a solution out there, and finally realizing that my problem can be solved by this solution.
The formalization of problem space + the discovery of solutions + the final realization of matching solutions to problems are non-trivial. I'm a bit embarrassed that it took so long and a bit sad. But it is what it is.
It usually comes from people who never had experience with statically typed languages, don't work on projects with a large dev team, cross teams projects or work with a lot of 3rd party libraries. They don't realize the maintenance nightmare that types can easy.
Sure you write one off script, or something that is rarely run don't use types, but when you have a 50k lines codebase that is actively developed and maintained it's another story.
I'm so glad Typescript changed that mindset of frontend developers and is supported by a lot of prominent open source projects
Thinking that typing is good and buying that a pasted-on-after-the-fact typing system is good are different matters.
Change is always hard.
That’s not to say that typing isn’t useful - I use it daily, especially since VSC has made it a lot faster than mypy - but I do think the Python community is wide enough that you can find people legitimately saying it is or isn’t a big deal for them as a function of where they work. You also have a certain amount of PTSD from languages like Java which make typing far more labor intensive and through some combination of limited expressiveness, dynamic logic, and culture end up making the benefits less than anticipated.
XML could have a similar approach although I'm not sure if anyone has done it already.
Second talk (30 minute mark) of this video, https://www.youtube.com/watch?v=ld9rwCvGdhc
Think for example a library like Pandas. Building something like that with a not-very-flexible type system would result in much more cumbersome user experience. In many cases you would likely feel the types just getting on your way while working interactively.
Microsoft has done great things with C# on this frontier, but it has also taken many years and probably a lot of brainpower.
If my project is something beyond a small script that I plan on working on on or off for a while, I do find that annotations definitely help. Also, it fuels IDE completions between functions if you annotate your input.
- you can use list[] instead of typing.List[]. Same for dicts or sets.
- you will be able to use bool | str instead of typing.Union[bool, str]
- mypy has saner default, is better supported by IDE and is way faster
- a lot of edge cases are now covered, including protocols for duck typing, vartype, etc.
- fantastic libs such as pydantic, fastapi and typer make using them a ton of fun
However, mypy is woefully limited when compared to TypeScript. Granted, TypeScript is maintained by a trillion dollar company while mypy is a community project.
One particularly interesting (though in my experience, rare) class of bugs are typing errors _in unit tests_. For example, an API under test expects one thing and a unit test supplies something else. If the test passes, it's hard to spot the problem without static type checking.