Pydantic V2 leverages Rust's Superpowers [video]
fosdem.org
fosdem.org
Beyond that, rust seems like a great fit for tooling (i.e. ruff), but as a library used at runtime, it seems a little odd to make a validation library (which can expect to receive any kind of legal python data) to also be constrained by a separate set of data types which are legal in rust.
msgspec[1] is another parsing/validation library, written in C. It's on average 50-80x faster than pydantic for parsing and validating JSON [2]. This speedup is only possible because we make use of native code, letting us parse JSON directly and efficiently into the proper python types, removing any unnecessary allocations.
It's my understanding that pydantic V2 currently doesn't do this (they still have some unnecessary intermediate allocations during parsing), but having the validation logic already in compiled code makes integrating this with the parser theoretically possible later on. With the logic in python this efficiency gain wouldn't be possible.
[1]: https://github.com/jcrist/msgspec
[2]: https://jcristharif.com/msgspec/benchmarks.html#benchmark-sc...
If you're interested in both efficiency and maintainability, I think you need to start by optimizing the language of origin. It seems to me that with pydantic, the choice has consistently been to jump to compilation (cython, now rust) without much attempt at optimizing within Python.
I'm not super-familiar with how things are being done on an issue-to-issue / line-to-line basis, but I see this rust effort taking something like a year+, when my intuition is some simpler speedups in python could have been in a matter of days or weeks (which is not to say they would be of the same magnitude of performance gains).
But the fact that it's faster than orjson (another native-code implementation) is cool.
This isn't really how writing rust/python iterop works. You tend to have opaque handles you call python methods on. Here's a decent example I found skimming the code.
https://github.com/pydantic/pydantic-core/blob/main/src/inpu...
That... makes no sense? Rust can interact with Python objects, there is no "constrained".
The argument for Rust: 1. If I'm going to rewrite - why not go the whole hog and do it in rust - and thereby get a 20x improvement, not 2x. 2. By using Rust we can have add more customisation with virtually no performance impact, with Python that's not the case.
Of course we could make Pydantic faster by removing features, but that would be very disappointing for existing user.
As mentioned by other commenters, your comment about "constrained" does not apply.
We use black at work. One of the challenges with it is that it doesn't play very nicely with pandas, specifically its abundant use of []. So we forked it and maintain a trivial patch that treats '[' the same as '.' and everybody's happy.
What was maybe 15 minutes of work for me to get everybody's buy-in to use a formatter would not have been so quick or easy if it had been written in rust and now either we maintain our own repo of binary wheels, or all our devs now need to include rust in their build tooling.
I'm not invested in the argument one way or the other, just wanted to note that having the stack be accessible to easy modification by any user is itself a feature and one some people (including me in general, not so much in this particular case) derive a lot of benefit from.
P.S. cheers and congratulations!
Have fun! I truly hope it pays the returns you hope it will as well.
Naysayers: you're welcome to fork the old python version. If the rust version is a nightmare for the ecosystem, I'm sure someone will do that.
I'm very excited to see the results!
Strange how it turned out that way, at the last convention everyone agreed that the best tool for python is rust... The silent majority was not there.
At least do it in Nim, a python dev can quickly catch up. Optimization kills resilience.
Pydantic2 is indeed much faster than any pure python implementation I've seen, but it also introduces some bugs. And on pypy it is as slow as it ever was, because it falls back to python code.
I wrote mine because nothing else existed at the time, but whenever I've had to use pydantic I've found it to be quircky and to have strange opinions about types, that are not shared by type validators. Using it with mypy (despite the extension) is not so easy nor useful.
I agree unions were wrong in V1, but smart unions helped, and unions are fixed properly in V2.
Of course there was an incompatible api change there, where the smart union parameter got removed and it's impossible to obtain the old (and completely wrong) behaviour. I'm sure someone relies on that.
[0]Maat is 2.5 times faster than Pydantic on their own benchmark, as stated in their readme.
This is nonsensical.
But people here just dislike algorithms and love to flag me. They gonna embrace their slow architecture in rust rather than do a better job in python.
[0] https://leerob.io/blog/rust#the-future-of-javascript-tooling
This is because the first crop, like mypy or babel or jslint existed, and has shown the general direction. But for the first crop, a slow-running but fast-turnaround language was essential, to my mind. The first iteration had to move fast, and change the direction fast, because it wasn't yet clear what direction was going to be right.
GitHub link to pydantic[1], and pydantic-core[2].
[0]: https://twitter.com/samuel_colvin/status/1649928041462915072 (slides in comments)
In contrast, when I designed Serialite [1], I designed it to have a Serializer base class with two abstract methods: to_data and from_data. Then I added a @serializable decorator that can be applied to any dataclass, which injects concrete implementations of to_data and from_data. The decorator is what I usually use, but I sometimes implement the base class directly when it gets too complicated.
Making Serialite work with FastAPI was almost impossible because there is no interface to implement, duck type or otherwise. In the end, Serialite monkey patches some key FastAPI functions to make them understand Serialite Serializers and that seems to work.
[0] https://slides.com/samuelcolvin/how-pydantic-v2-leverages-ru...
Edit: Realized that the linked slides were from a different iteration of the ~same content.
Transcript: https://jonatron.github.io/fosdem2023whisper/files/rust_how_...
(transcribed with whisper)
How in the world can I stop worrying about errors like using a non existant class member and having a runtime exception? How can I refactor?
Ok, the core devs add annotations, then type hints to the language.
Some other people create MyPy, the JetBrains people use some other linting thing that does well, but does not match MyPy. The Pydantic appear and some other people says its awesome, but yet again, different to the others...
And all that to enforce things we already had 20 years ago in Java 1.0
How about using dynamic typing for small script and prototyping and using better tools for bigger projects?
Unless your objectives are not commercial or will never scale beyond the ability of a single person, the overhead of human communication and collaboration will be enormous compared the inefficiencies of shuffling electrons and flipping bits with imperfect instructions. Sometimes this means using technically-inferior tools better than idealistic tools improperly to get the job done.
It's not a great language in a vacuum... but it is the most popular backend language in the world, by most estimations; there's a library for literally everything, and the entire data science ecosystem lives in the Python world. If you're on the management side, hiring a Python developer is orders of magnitudes easier than finding a Rust developer.
So you've really only got a few options... 1) throw everything out to rewrite it in Rust (et al); 2) accept that things suck and do nothing about it; 3) accept that things suck, but make some tooling to make it suck less. The rewrite strategy is a nonstarter for a lot of massive legacy codebases, so 3 is the only option that makes sense.
So it's really not that amazing how much time people invest in improving Python, when you think about it. Similar situation with PHP and Javascript.
Good, because people have done actual surveys to show there's no real decrease in bugs, and development time suffers: https://arxiv.org/abs/2203.11115
It's a trade off like anything else, Python has a lot of scientists who probably love not having to specify types everywhere. Python's best advantage is ease of development - Rust is in _no way_ an alternative in that department. Go would be a better choice.
It's biggest issue imo is it's slow, but since people aren't rushing to use mypy and friends, perhaps that's not important for most users. And it's had types for ages if you want them.
> The analysis indicates that TS apps exhibit significantly better code quality and understandability than JS apps [...] Furthermore, reducing the usage of the `any` type in TS apps was significantly correlated with all metrics except bug proneness.
> It's biggest issue imo is it's slow, but since people aren't rushing to use mypy and friends, perhaps that's not important for most users.
People are rushing to mypy. Every Python library now has type stubs available. That wasn't the case even 3-4 years ago. Similar story with the mass move to TypeScript, which currently is the fastest-growing language[0].
Dynamic typing[1] is a legacy of ignorance and immaturity in the industry, from the same era where it was common to put your php $_GET parameters directly into a SQL query or access your C array without bounds checking. For the most part, the industry is smarter than this now, thankfully.
[0] https://visualstudiomagazine.com/articles/2023/02/02/jetbrai...
[1] note I'm really getting at "dynamic by default" -- there's certainly a use case for objects whose structures are only known at runtime, but that should be the exception, not the rule.
People are rushing to mypy for type checking, not speed improvements. I use cypthon and VS Code still does type checking for me; I don't care what program is doing it.
My argument is that truly static typing is too extreme in the other direction. Many times you don't care about type checking - quick scripts, data science, handling large JSON blobs - and informing the compiler is just boilerplate work. So I think we agree there that a static language with an 'any' type, like TypeScript, is the happy medium here.
It's not popular purely based on its merits as a language
Python is indispensable for interactive experimentation (see Jupyter), and is a good glue language (see everything from Pytorch to Blender). It's also indispensable for rapid prototyping.
Python is not a good high-performance language. If performance is something that limits you, you should write performance-critical parts in a language optimized for that. Rust is a fine choice, but many other options exist, from Java to Haskell, and Python-integrated solutions like Cython also help. Note that usually 80-90% of your code is not performance-critical.
Same applies to systems where you want to formally prove certain correctness properties; both Python and C would be terrible choices.
By the same token, Rust is not a terrible language, despite its complicated syntax, the constant struggle with lifetimes and the borrow checker, and long compilation times. It shines when you need performance and correctness. If you need easy experimentation in a REPL, use a different language.
Use the right tool for the job.