10 ms·
Pyre: A performant type-checker for Python 3
- azhenley 6y agoBig discussion with over 500 comments from 3 years ago: https://news.ycombinator.com/item?id=17048446 https://news.ycombinator.com/item?id=17048446
- flakiness 6y agoSo three years passed and static checkers have gotten even more traction. What's the best option for Python so far for small projects today? I tried mypy [1] before but it was a bit cumbersome to keep it checking my code. At work I use pytype [2]. It's good enough but that's only because someone else made a build system integration for me. Pyre's scan-all-the-files approach seems easier to get started. Is there any catch? Which one are you using and what's your impression? [1] https://mypy.readthedocs.io/en/stable/ [2] https://github.com/google/pytype
- hiq 6y agoAs someone who hasn't started using types in Python seriously yet, it's a bit discouraging to see that there are already so many competing type checkers with different approaches and no clear winner. I understand that the problem is a bit harder than `{go, cargo} fmt`, but I feel we'd be better off with one type checker to rule them all. Or does it mean that we should check types using all type-checkers available to have the most compliant code possible?
- Mehdi2277 6y agoIn practice they are quite similar in errors reported. There are differences that pop up but most of the time either it is bug to report or one has implemented a certain pep faster than another. A few rare things are extra type checking support entirely like pyright supports recursive types but mypy does not (or pyre has best tensor related support but those are future peps). Mypy's biggest unique thing is plugin support and some very dynamic libraries use plugins for better coverage. The differences should become peps if important enough and then eventually be supported by all 4. I think for most people any of the 4 big ones is fine. Most of the common type errors will look identical regardless of which you pick. Configuring multiple in CI is pretty straightforward if you want to go full. My current codebase has mypy + pyright configured. Pyright was a mix of fast response time on github issues + I use vscode and was the one that added type checks to CI. If you want a deep dive pycon is this week I think and there's a day for type checking related talks including one talk comparing the 4. I think type checking day is thursday.
- flakiness 6y agoThanks for the tip! Posting link here for the reference: https://us.pycon.org/2021/summits/typing/ https://us.pycon.org/2021/summits/typing/ Hope they post the recordings somewhere later.
- ben509 6y agoNo, multiple checkers will drive you crazy because one type checker will support one feature while another will report errors for it.
- pl-94 6y agoI personally use neovim with coc-pyright plugin. It integrates remarkably well mypy. It has saved me so many hours of development, I just can't dev without it nowadays.
- MapleWalnut 6y agoI've used mypy and pyright. Mypy generally "just works" for all the Python idioms I use, while pyright is less reliable. Pyright's VSCode integration, Pylance, provides a great auto complete experience. So I use Pyright for autocomplete in VSCode and mypy for type checking.
- throwaway894345 6y agoLast I checked, mypy struggled to represent recursive types. Think `JSON = Union[None, bool, str, float, int, List['JSON'], Dict[str, 'JSON']`. That's a bummer because recursive data types are darn handy. Worse, importing third party packages often fails silently and when you can get error messages they tend to be completely inactionable (I recall one error message which linked to a web page that had lots of details and workarounds for fixing other problems, but none of which solved the error itself). Figuring out how to distribute my own type annotations was similarly painful. IIRC, you have to drop a specially-named file into a particular directory and this is all undocumented save for a dense PEP and the error messages are unsurprisingly terrible. All of these things are actionable, but the progress seems slow (these have been among my top grievances since the project debuted, so the maintainers and I have different priorities, clearly). The problems for which I'm less optimistic tend to revolve around shoehorning typing into existing Python syntax--e.g., to get a callback that takes kwargs you have to define a protocol with a `__call__` method that takes kwargs because you can't express it with `typing.Callable`. Similarly where a language with first-class support for types might have `type Foo<T>`, Python makes you write `T = TypeVar("T"); class Foo(Generic[T])` or something like that, and it gets more confusing when you only want one of the methods to be generic and I can never remember whether that `T` takes on a single type across all uses or which scope I need to define it in, etc. This is largely an ergonomic nightmare and I don't have lots of optimism for this stuff to improve unless the Python community really comes to embrace typing as the default way to use Python (but I suspect most people who care a lot about this kind of stuff will leave for Go or other languages where these things just work out of the box).
- codethief 6y ago> Similarly where a language with first-class support for types might have `type Foo<T>`, Python makes you write `T = TypeVar("T"); class Foo(Generic[T])` or something like that, and it gets more confusing when you only want one of the methods to be generic and I can never remember whether that `T` takes on a single type across all uses or which scope I need to define it in, etc. I don't know about you but I find PEP 484 very clear here: https://www.python.org/dev/peps/pep-0484/#scoping-rules-for-type-variables https://www.python.org/dev/peps/pep-0484/#scoping-rules-for-...
- zem 6y agohave you had any problems using the open source version of pytype? we've tried to make it easy to just drop in to your setup.cfg and automatically analyse an entire project; if there are things that don't work we'd love bug reports for them!
- flakiness 6y agoNo. I didn't expect it to be non-blaze/bazel tool friendly, but sounds like it is (aims to be at lest)? It does seems to support the entire-directory parsing as well. That's nice! Let me give it a try next time. Thanks for the tip! As a reminder to myself, here is the link to the doc: https://google.github.io/pytype/ https://google.github.io/pytype/
- tomwojcik 6y agoI'd advise to give mypy yet another try but disable in config file error codes that are painful and # noqa or # type: ignore lines that can't be understood well by mypy.
- nickm12 6y agoI'm not sure what you mean by "cannot be understood well". Either the type annotation is correct or not. If there is a genuine bug in mypy, the recommended convention is to use "type: ignore" (ideally with a reference to a bug tracking id). If you are genuinely subverting the typesystem, then use a cast(). If the code is too complex to type correctly or the type cannot be expressed in the typesystem (e.g. recursive types) then use type Any.
- 6gvONxR4sf7o 6y agoWhichever option you take, stick it into pre-commit. A good pre-commit-config.yaml is quality-of-life changing.
- jchonphoenix 6y agoMypy and Pyre appear to be the only two that work really well and can solve type-checking issues at scale.
- dunefox 6y agoAs with package managers, there seem to be half a dozen different, competing type checkers for Python now...
- IshKebab 6y agoYeah and even worse they disagree about type errors! We really need a modern Python alternative. I don't know of any that don't give up the REPL / single file script features which are pretty huge advantages of Python to be honest.
- iudqnolq 6y agoIt's radically different, but the language where I've had the most pleasant repl-driven experience is Elixir. Because of how it's error handling works it's even sane to debug with a repl into live production in some cases.
- fish45 6y agoI've started learning Elixir over the week and I can't see myself using Python for scripting again. They're very different languages but th experience feels similar, except I vastly prefer Elixir
- iudqnolq 6y agoI wouldn't expect elixir to be good at scripting. What sort of libraries do you use?
- Sohcahtoa82 6y agoNode.js has a REPL, and there's nothing stopping you from putting your entire project into a single file.
- IshKebab 6y agoTrue, but to use JavaScript sensibly you really need to use Typescript and ESLint (to ban the crazy old features like `var` and `==`). But I do agree Typescript is one of the best alternatives today if you can stomach `tsconfig.json` `eslintrc` and `node_modules`.
- brobinson 6y agoWe unfortunately had to switch away from this as it took too long for pyre to support Python 3.8 after it was released. I've been using mypy since then, but I had no complaints about pyre when I used it.
- jmugan 6y agoPyCharm works well for me. Probably not as fancy as all this other stuff, but the type hints make the code easier to understand, and they help PyCharm help me by enabling it to find more errors and by enabling enhanced autocompletion.
- kbumsik 6y agoWhat type checker does PyCharm use? In-house?
- whimsicalism 6y agoYes, in house
- nerdponx 6y agoPyCharm having type checking built in is excellent, but it is definitely the lowest quality out of the major 3 (Mypy, Pyright, Pyre) with respect to correctness.
- vorticalbox 6y agoI've always found its type checking to be perfectly fine, but hearing its not the best I might look into the others.
- nerdponx 6y agoIt tends to be overly-lenient about certain return types and tends to miss some more advanced type inferences. It's a great tool when editing code. But you still should run Mypy or another checker for more-correct analysis.
- a3w 6y agoA Tale of two types systems -> now: a Tale of three types systems? To make it a book title, The three type systems problem?
- Demiurge 6y agoHow are three type systems? The type annotations are part of the Python 3. You can use multiple libraries to analyze the types. There are also multiple static type analysis tools for C, and for other languages that have type definitions as part of the language. How is this an issue, what am I missing something?
- erjiang 6y agoWhen you write types in Python, the interpretation of your type annotations are up to the type checker. Your annotations that you write for e.g. Pyre may not type check in mypy. The end result is that your type annotations are not "Python" type annotations, but "Pyre"/"mypy"/etc. type annotations. In C, you ultimately care about what the compiler says. And this has also led to dialect-specific C code that works fine in one compiler but doesn't compile or runs incorrectly in another compiler.
- Mehdi2277 6y agoNot that much as they all follow pep 484 + a few other peps. The number of type features unique to each one are generally bugs/recent peps they haven't implemented. The biggest one is mypy plugin ecosystem although the hope there is to either do more peps that plugins become no longer needed and the type system is strong enough to cover more things or make a plugin pep. If you are using the most recent pep features possible than yeah you might have an issue. That's similar to clang/gcc both taking time to implement new c++ standards and not being compatible there. If you only use pep 484 which covers most basics well then you should be good for any checker.
- staticassertion 6y ago> Not that much as they all follow pep 484 + a few other peps. The number of type features unique to each one are generally bugs/recent peps they haven't implemented. This is totally untrue? Pyre adds completely new notions like taint analysis, pytype adds a totally different inference system - the type systems are not compatible and it has nothing to do with implementation of PEPs. The difference with C is that all of the other linters and analyzers are on top of the base type system, they don't replace it. In the case of Python the only standard part is where the annotations go and how they get resolved at runtime, it's otherwise completely up to the type system implementation to determine what's what, and all 3 of them do so in very different ways. This is like if clang/gcc had totally different behaviors for `auto` in C++, but really it's not even comparable.
- globular-toast 6y agoAnyone considering using type hints should listen to this talk: https://www.infoq.com/presentations/dynamic-static-typing/ https://www.infoq.com/presentations/dynamic-static-typing/ I personally think it's mostly a waste of time to do type hinting for the purpose of catching errors in a strongly typed language like Python. Type errors just aren't practically a problem in dynamic languages. Doing types for performance is a great reason to do it, though.
- mumblemumble 6y agoI agree with you that the benefits of static typing are sometimes greatly exaggerated. But I also think that using type hints and type checkers in Python isn't quite the same thing as static typing. For starters, type checking can't actually guarantee you won't have type errors at run time. Because, unlike in a statically typed language, in Python, anyone can always choose to just not use type hinting. Whenever that happens, as far as the type checker is concerned, anything goes. But type hints are very useful as hints. They help with editor tooling, which can make it easier to navigate an unfamiliar codebase. They provide extra information that makes the code easier to read. And they give me an opt-in form of type linting that allows me to set up regions of code where I don't have to take quite so much personal responsibility for ensuring that arguments are compatible with parameters. In short, it's not a correctness prover; it's an energy saver.
- flowerlad 6y ago> I agree with you that the benefits of static typing are sometimes greatly exaggerated. For large, multi-developer projects, it is impossible to exaggerate the benefits of static typing.
- deleted 6y ago[deleted]
- nickm12 6y agoI don't like the term "type hints" because typecheckers like mypy are genuinely proving type correctness. Yes, if you don't annotate part of your program then you can get a type error in that part of the program, likewise, if you pass a value of the wrong type, you can get a type error. But if you are using a typechecker, you are guaranteed that if your inputs are well-typed, then you won't have a type error, which is a stronger guarantee than "hints" implies.
- skrtskrt 6y agoBeen using coc-pyright with coc.nvim and I am a fan. Issues seem to be from libraries with crappy, incomplete, or incorrect typing/stubs, not from the checker itself. Every day I tire more and more of using Python for larger projects for these reasons
- j1elo 6y agoUnrelated funny little fact for lovers of scifi novels: Pyre (PyrE) was the name of an extremely rare element and main plot device for the novel Tiger! Tiger! (aka. "The Stars My Destination"), by Alfred Bester: https://www.amazon.com/dp/B01MRJVUPC/ https://www.amazon.com/dp/B01MRJVUPC/ Maybe not the best science fiction book of all times, but it left a mark on my memory... and curious things like this name have stayed there since when I was a kid avidly reading everything that fell on his hands :-) -- EDIT: Link to the book
- jl2718 6y agoI see a statically-typed jit-compiled python fork coming.
- emipop 6y agoIs it just me or does type checking python break the idea of python? If you wanted type checking shouldn't you just use a different language that has a sensible type model to begin with?