Latest / Talk Python To Me / #442: Ultra High Speed Message Parsing with msgspec
Transcript
- 0:00If you're a fan of Pydantic or data classes, you'll definitely be interested in this episode.
- 0:04We are talking about a super fast data modeling and validation framework called msgspec.
- 0:09And some of the types in here might even be better for general purpose use than Python's
- 0:15native classes.
- 0:15Join me and Jim, Chris Hariff, to talk about his framework, msgspec.
- 0:19This is Talk Python To Me, episode 442, recorded November 2nd, 2023.
- 0:25Welcome to Talk Python To Me, a weekly podcast on Python.
- 0:43This is your host, Michael Kennedy.
- 0:44Follow me on Mastodon, where I'm @mkennedy, and follow the podcast using @talkpython,
- 0:49both on fosstodon.org.
- 0:52Keep up with the show and listen to over seven years of past episodes at talkpython.fm.
- 0:57We've started streaming most of our episodes live on YouTube.
- 1:01Subscribe to our YouTube channel over at talkpython.fm/youtube to get notified about upcoming
- 1:06shows and be part of that episode.
- 1:08This episode is sponsored by Posit Connect from the makers of Shiny.
- 1:14Publish, share, and deploy all of your data projects that you're creating using Python.
- 1:19Streamlit, Dash, Shiny, Bokeh, FastAPI, Flask, Reports, Dashboards, and APIs.
- 1:24Posit Connect supports all of them.
- 1:27Try Posit Connect for free by going to talkpython.fm/posit, P-O-S-I-T.
- 1:32And it's brought to you by us over at Talk Python Training.
- 1:36Did you know that we have over 250 hours of Python courses?
- 1:41Yeah, that's right.
- 1:42Check him out at talkpython.fm/courses.
- 1:45Jim.
- 1:48Hello.
- 1:48Hello.
- 1:48Welcome to Talk Python.
- 1:49It's awesome to have you here.
- 1:50Yeah.
- 1:51Thanks for having me.
- 1:51Yeah, of course.
- 1:52I spoke to the Litestar guys, you know, at Litestar.dev and had them on the show.
- 1:57And I was talking about their DTOs, different types of objects they can pass around in their
- 2:03APIs and their web apps.
- 2:04And like FastAPI, they've got this concept where you kind of bind a type, like a class
- 2:09or something, to an input, to a web API.
- 2:12And it does all that sort of magic like FastAPI.
- 2:15And I said, oh, so you guys probably work with PyDanty.
- 2:17It's like, yes, but let me tell you about msgspec.
- 2:19Because that's where the action is.
- 2:21They were so enamored with your project that I just had to reach out and have you on.
- 2:25It looks super cool.
- 2:26I think people are going to really enjoy learning about it.
- 2:28Thanks.
- 2:29Yeah, it's nice to hear that.
- 2:30Yeah.
- 2:31We're going to dive into the details.
- 2:33It's going to be a lot of fun.
- 2:33Before we get to them, though, give us just a quick introduction on who you are.
- 2:37So people don't know you yet.
- 2:39So my name is Jim Christreif.
- 2:41I am currently an engineering manager doing actually mostly dev work at Voltron Data, working
- 2:47on the IBIS project, which is a completely different conversation than what we're going to have today.
- 2:51Prior to that, I popped around a couple of startups and was most of them doing Dask was the main
- 2:58thing I've contributed to in the past on an open source Python front.
- 3:01For those not aware, Dask is a distributed compute ecosystem.
- 3:04I come from the PyData side of the Python ecosystem, not the web dev side.
- 3:09Nice.
- 3:09Yeah, I've had Matthew Rocklin on a couple of times, but it's been a while, so people don't
- 3:13necessarily know.
- 3:13But it's like super distributed pandas, kind of.
- 3:18Grid computing for pandas, sort of.
- 3:20Or say like Spark written in Python.
- 3:22Sure.
- 3:23You know, another thing that's been on, kind of on my radar, but I didn't really necessarily
- 3:27realize it was associated with you.
- 3:29Tell people just a bit about IBIS.
- 3:31Like IBIS is looking pretty interesting.
- 3:33IBIS is, I don't want to say the wrong thing.
- 3:35IBIS is a portable data frame library is the current tagline we're using.
- 3:39If you're coming from R, it's dplyr for Python.
- 3:42It's more than that.
- 3:43And it's not exactly that, but that's a quick mental model.
- 3:46So you write data frame like code.
- 3:49We're not pandas compatible.
- 3:50We're pandas like enough that you might find something familiar.
- 3:53And it can compile down to generate SQL for 18 plus different database backends.
- 3:58Also like PySpark and a couple other things.
- 4:01Okay.
- 4:01So you write your code once and you kind of run it on whatever.
- 4:03I see.
- 4:03And you do pandas like things, but it converts those into database queries.
- 4:08Is that?
- 4:08Yeah.
- 4:09Yeah.
- 4:09So it's a data frame API.
- 4:10It's not pandas compatible, but if you're familiar with pandas, you should be able to pick it up.
- 4:16You know, we cleaned up what we thought as a bunch of rough edges of the pandas API.
- 4:19Yeah.
- 4:19Were those pandas one or pandas two rough edges?
- 4:22Both.
- 4:22It's, I don't know.
- 4:23It's pandas like.
- 4:25Sure.
- 4:25Yeah.
- 4:26This looks really cool.
- 4:27That's a topic for another day, but awesome.
- 4:29People can check that out.
- 4:30But this time you're here to talk about your personal project, msgspec.
- 4:37Am I saying that right?
- 4:38Or you say MSG or msgspec?
- 4:40Message spec is how it is.
- 4:42I think a lot of these projects sometimes need a little, like here's the MP3 you can press play on.
- 4:48Like how it's meant to be said, you know?
- 4:50I mean, sometimes it's kind of obvious, like PyPI versus PyPI.
- 4:55Other times it's just like, okay, I know you have a really clever name.
- 4:58Yes, I know.
- 4:59People say NumPy all the time.
- 5:01I'm like, I don't want to, I try to not correct guests because it's, it's not kind.
- 5:05But I also feel awkward.
- 5:06They will say NumPy and I'll say, how do you feel about NumPy?
- 5:08Like NumPy's great.
- 5:09I'm like, okay, we're just going back and forth like this for the next hour.
- 5:12It's fine.
- 5:12But yeah, it's, it's always, I think some of these could use a little, like a little play.
- 5:17So msgspec.
- 5:18Tell people about what it is.
- 5:19Yeah.
- 5:20So gone through a couple of different taglines.
- 5:22The current one is a fast serialization and validation library with a built-in support for
- 5:26JSON, message pack, YAML, and TOML.
- 5:29If you are familiar with Pydantic, that's probably one of the closest, you know, most popular libraries
- 5:34that does a similar thing.
- 5:35You define kind of a structure of your data using type annotations and msgspec will parse
- 5:40your data to ensure it is that structure and does so efficiently.
- 5:44It's also compatible with a lot of the other serialization libraries.
- 5:48You could also use it as a stand-in for JSON, you know, with the JSON dumps, JSON loads.
- 5:53You don't need to specify the types.
- 5:55Right.
- 5:55It's, I think the mental model of kind of like, it swims in the same water or the same pond
- 6:01as Pydantic, but it's also fairly distinguished from Pydantic, right?
- 6:06As we're going to explore throughout our chat here.
- 6:09The goal from my side, one of the goals was to replicate more of the experience writing
- 6:14Rust or Go with Rust-SERDE or Go's JSON, where the serializer kind of stands in the background
- 6:19rather than my experience working with Pydantic, where it felt like the base model kind of stood
- 6:24in the foreground.
- 6:25You're defining the model.
- 6:27Serialization kind of comes onto the types you've defined, but you're not actually working
- 6:30with the serializers on the types themselves.
- 6:32Got it.
- 6:32So an example, let me see if I do have it.
- 6:35An example might be if I want to take some message I got from, some response I got from
- 6:41an API, I want to turn it into a Pydantic model or I'm writing an API.
- 6:44I want to take something from a client, whatever.
- 6:46I'll go and create a Pydantic class.
- 6:48And then the way I use it is I go to that class and I'll say star, star, dictionary I got.
- 6:55And then it comes to life like that, right?
- 6:57Where there's a little more focus on just the serialization and it has this capability.
- 7:03But like you said, it's optional in the sense.
- 7:06Yeah.
- 7:06In msgspec, all types are on equal footing.
- 7:11So we use functions, not methods, because if you want to decode into a list of ints, I
- 7:17can't add a method to a list.
- 7:18You know, it's a Python built-in type.
- 7:20Yeah.
- 7:20So you'd say msgspec dot JSON dot decode your message and then you'd specify the type
- 7:26annotation as part of that function call.
- 7:29So it could be, you know, list bracket int.
- 7:31Right.
- 7:31So you'll say decode and then you might say type equals list of your type or like you
- 7:37say, list of int.
- 7:37And that's hard when you have to have a class that knows how to basically become what the
- 7:42model, the data passed in is, even if it's just a list, some Pydantic classes, you got
- 7:48to kind of jump through some hoops to say, hey, Pydantic, I don't have a thing to give
- 7:52you.
- 7:52I want a list of those things.
- 7:54And that's the top level thing is, you know, bracket bracket.
- 7:56It's not, it's not any one thing I can specify in Python easily.
- 8:00Yeah.
- 8:00To be fair to the Pydantic project, I believe in V2, the type adapter.
- 8:04Yes, exactly.
- 8:05Object can work with that.
- 8:06But that is, you know, it's a different way of working with it.
- 8:09I wanted to have one API that did it all.
- 8:12Sure.
- 8:12And it's awesome.
- 8:13They made it.
- 8:13I mean, I want to just put this out front.
- 8:15Like, I'm a massive fan of Pydantic.
- 8:17What Samuel's done there is incredible.
- 8:19And it's just, it's really made a big difference in the way that people work with data and Python.
- 8:24It's awesome.
- 8:25But it's also awesome that you have this project that is an alternative and it makes different assumptions.
- 8:29And you can see those really play out in like the performance or the APIs.
- 8:33So, you know, like Pydantic encourages you to take your classes and then send them the data.
- 8:39But you've kind of got to know, like, oh, there's this type adapter thing that I can give a list of my class and then make it work.
- 8:45Right.
- 8:45But it's not just, oh, you just fall into that by trying to play with the API, you know?
- 8:50Yeah.
- 8:51Yeah.
- 8:51And I think having, being able to specify any type means we work with standard library data classes.
- 8:56The same as we work with our built-in struct type or we also work with attrs types.
- 9:00You know, everything is kind of on equal footing.
- 9:02Yeah.
- 9:02And what I want to really dig into is your custom struct type that has some really cool properties.
- 9:10Not class properties, but components.
- 9:11Features of the class of the type there.
- 9:14Yeah.
- 9:14Let's look at a couple of things here.
- 9:16So, as you said, it's fast and I love how somehow italicies on the word fast makes it feel even faster.
- 9:23Like it's leaning forward, you know, it's leaning into the speed.
- 9:26A fast serialization and validation library.
- 9:28The validation is kind of can be, but not required, right?
- 9:32The types can be, but they don't have to be.
- 9:34So, I think that's one of the ways it really differs from Pydantic.
- 9:37But the other is Pydantic is quite focused on JSON, whereas this is JSON, message pack, YAML, and TOML.
- 9:45Everyone knows what JSON is.
- 9:47I always thought of TOML as kind of like YAML.
- 9:49Are they really different?
- 9:51It's another configuration focused language.
- 9:54I think some people do JSON for config files, but I personally don't like to handwrite JSON.
- 9:59YAML and TOML are like more human friendly, in quotes, forms of that.
- 10:04YAML is a superset of JSON.
- 10:06TOML is its own thing.
- 10:08Got it.
- 10:08And then message pack is a binary JSON-like file format.
- 10:12Yeah, message pack.
- 10:13I don't know how many people work with that.
- 10:15Where would people run into message pack?
- 10:16Yeah.
- 10:17If they were, say, consuming an API, or what API framework would people be generating message
- 10:22pack in Python, typically?
- 10:23That's a good question.
- 10:24So, going back to the creation of this project, actually, msgspec sounds a lot like message
- 10:29pack.
- 10:30And that was intentional.
- 10:30It does, yeah.
- 10:31Because that's what I wrote it for originally.
- 10:33So, as I said at the beginning, I'm one of the original contributors to Dask.
- 10:37Worked on Dask forever.
- 10:38And the Dask distributed scheduler uses message pack for its RPC serialization layer.
- 10:43That kind of fell out of what was available at the time.
- 10:46We benchmarked a bunch of different libraries.
- 10:48And that was the fastest way to send bytes between nodes in 2015.
- 10:52Sure.
- 10:53The distributed scheduler's RPC framework has kind of grown haphazardly over time.
- 10:58And there were a bunch of bugs due to some hacky things we were doing with it.
- 11:01And also, it was slower than we would have wanted.
- 11:03So, this was an attempt to write a faster message pack library for Python that also did
- 11:09fancier things.
- 11:10Supported more types.
- 11:11Did some schema validation because we wanted to catch the worker is sending this data and
- 11:16the scheduler is getting it and saying it's wrong.
- 11:18And we wanted to also add in a way to make schema evolution, meaning that I can have different
- 11:25versions of my worker and scheduler and client process and things kind of work.
- 11:28If I add new features to the scheduler, they don't break the client.
- 11:33You know, we have a nice forward and backward compatibility story.
- 11:36And so, that's what kind of fell out.
- 11:38Yeah, it's a really nice feature.
- 11:39We're going to dive into that.
- 11:40But, you know, you might think, oh, well, just update your client or update the server.
- 11:45But there's all sorts of situations that get really weird.
- 11:47Like, if you have Redis as a caching layer and you create a message pack object and stick
- 11:54it in there and then you deploy a new version of the app, it could maybe can't,
- 11:58deserialize anything in the cache anymore because it says something's missing or something's
- 12:02there that it doesn't expect.
- 12:04Right.
- 12:04And so, this evolution is important there.
- 12:07If you've got long running work and you stash it into a database and you pull it back out,
- 12:10like all these things where it kind of lives a little outside the process, all of a sudden
- 12:14it starts to matter that before you even consider like clients that run separate code.
- 12:19Right.
- 12:19Like you could be the client, just different places in time.
- 12:22Yeah.
- 12:22Yeah.
- 12:23So, adding a little bit more structure to how you define messages in a way to make the
- 12:26scheduler more maintainable.
- 12:27That work never landed.
- 12:28It's as it is with open source projects.
- 12:31It's a democracy and also a democracy.
- 12:33And, you know, you don't always, paths can be done at dead ends.
- 12:36I still think it'll be valuable in the future, but some stuff was changing the scheduler and
- 12:40serialization is no longer the bottleneck that it was two and a half years ago when this originally
- 12:45started.
- 12:46So, let me put this in context for people to maybe make it relevant.
- 12:49Like maybe right now someone's got a FastAPI API and they're using Pydantic and obviously
- 12:55it generates all the awesome JSON they want.
- 12:58Is there a way to, how would you go about creating, say, a Python server-based system set
- 13:06of APIs that maybe as an option take message pack or maybe use that as a primary way?
- 13:11Like it could be maybe, you know, passing an accept header.
- 13:14To take message pack?
- 13:15If you want to exchange message pack, client server, Python right now, what do you do?
- 13:19That's a good question.
- 13:20To be clear, I am not a web dev.
- 13:22I do not do this for a living.
- 13:23I think there is no standard application slash message pack.
- 13:26I think people can use it if they want, but that's not a, it's a standardized thing the
- 13:31same way that JSON is.
- 13:32Yeah.
- 13:32I think that Litestar as a framework does support this out of the box.
- 13:35I don't know about FastAPI.
- 13:37I'm sure there's a way to hack it in as there is with any ASGI server.
- 13:41Yeah, Litestar, like I said, I had Litestar on those guys maybe a month ago and...
- 13:45Yeah, super, super cool about that.
- 13:47So, yeah, I know that they support msgspec and a lot of different options there, but,
- 13:52you know, you could just, I imagine you could just return binary bits between you and your
- 13:57client.
- 13:58I'm thinking of like latency sensitive microservice type things sort of within your data center.
- 14:04How can you lower serialization, deserialization, serialization, like all that cost that could
- 14:08be the max, you know, the biggest part of what's making your app spend time and energy?
- 14:14Michael out there says, would love PyArrow parquet support for large data.
- 14:18There's been a request for Aero integration with msgspec.
- 14:22I'm not exactly sure what that would look like.
- 14:24Aero containers are pretty efficient on their own.
- 14:26Breaking them out into a bunch of objects or stuff to work with msgspec doesn't necessarily
- 14:31make sense in my mind.
- 14:32But anyway, if you have ideas on that, please open an issue or comment on the existing issue.
- 14:36Yeah, indeed.
- 14:37All right.
- 14:38So let's see.
- 14:39Some of the highlights are high performance encoders and decoders across those protocols
- 14:43we talked.
- 14:44You have benchmarks.
- 14:45We'll look at them for in a minute.
- 14:46You have a really nice, a lot of support for different types that can go in there that
- 14:51can be serialized, but there's also a way to extend it to say, I've got a custom type that
- 14:56you don't think is serializable to whatever end thing, a message pack, JSON, whatever.
- 15:01But I can write a little code that'll take it either way.
- 15:04You know, dates are something that drive me crazy, but it could be like an object ID out
- 15:09of MongoDB or other things that seem like they should go back and forth, but don't, you know,
- 15:13right?
- 15:13So that's really nice.
- 15:14And then zero cost schema validation, right?
- 15:18It validates, decodes and validates JSON two times as fast as ORJSON, which is one of
- 15:22the high performance JSON decoders.
- 15:24And that's just decoding, right?
- 15:26And then the struct thing that we're going to talk about, which the struct type is kind
- 15:30of what brings the parody with Pydantic, right?
- 15:33Yeah.
- 15:34You could think of it as Pydantic's base model.
- 15:36It's our built-in data class-like type.
- 15:38Nice.
- 15:38So structs are data class-like.
- 15:40Like everything in msgspec are implemented fully as a C extension.
- 15:45Getting these to work required reading a lot of the CPython source code because we're doing
- 15:50some things that I don't want to say that they don't want you to do.
- 15:54We're not doing them wrong, but they're not really documented.
- 15:57So for example, when you subclass for msgspec.struct, that's using a metaclass mechanism,
- 16:03which is a way of defining types to define types.
- 16:06And the metaclass is written in C, which CPython doesn't make easy to do.
- 16:11So it's a C extension metaclass that creates new C types.
- 16:16They're pretty speedy.
- 16:17They are 10 to 100x faster for most operations than even handwriting a class that does the
- 16:23same thing, but definitely more than data classes or attrs.
- 16:25Yeah.
- 16:26It's super interesting.
- 16:27And I really want to dive into that.
- 16:28I almost can see the struct type being relevant even outside of msgspec in general, potentially.
- 16:34So yeah, we'll see about that.
- 16:36But it's super cool.
- 16:37And Michael also points out, like, he's the one who made the issue.
- 16:40So sorry about that.
- 16:42He's commented already, I suppose, in a sense.
- 16:45But yeah, awesome.
- 16:46Cool.
- 16:47All right.
- 16:47So let's do this.
- 16:49I think probably the best way to get started is we could talk through an example.
- 16:53And there's a really nice article by Itmar Turner-Trowing, who's been on the show a couple
- 16:59of times, called Faster, More Memory-Efficient Python, JSON parsing with msgspec.
- 17:04And just as a couple of examples that I thought maybe we could throw up.
- 17:06And you could talk to, speak to your thoughts, like, why does the API work this way?
- 17:11Here's the advantages and so on.
- 17:13Yeah.
- 17:13So there's this big, I believe this is the GitHub API, just returning these giant blobs of stuff
- 17:17about users.
- 17:18Okay.
- 17:19And it says, well, if we want to find out what users follow what repos or how many,
- 17:24given a user, how many repos do they follow, right?
- 17:27We could just say, with open, read this, and then just do a JSON load.
- 17:31And then do the standard dictionary stuff, right?
- 17:34Like, for everything, we're going to go to the element that we got out and say, bracket some
- 17:38key, bracket some key.
- 17:40You know, it looks like key not found errors are just lurking in here all over the place.
- 17:44But, you know, it's, you should know that maybe it'll work, right?
- 17:48If you know the API, I guess.
- 17:49So it's like, this is the standard way.
- 17:51How much memory does this use?
- 17:52How much time does it take?
- 17:53Look, we can basically swap out ORJSON.
- 17:57I'm not super familiar with ORJSON.
- 17:59Are you?
- 17:59Yeah.
- 18:00ORJSON is compatible-ish with the standard lib JSON, except that it returns bytes rather
- 18:05than strings.
- 18:06Got it.
- 18:06Okay.
- 18:07There's also iJSON, I believe, which makes it streaming.
- 18:10So there's that.
- 18:11And then it says, okay, well, how would this look if we're going to use msgspec?
- 18:15And in his example, he's using structured data.
- 18:19So the structs, this is like the Pydantic version, but it doesn't have to be this way,
- 18:23but it is this way, right?
- 18:25This is the one he chose.
- 18:26So maybe just talk us through, like, how would you solve this problem using message
- 18:30spec and classes?
- 18:31Yeah.
- 18:31So as he's done here in this blog post, he's defined a couple struct types for the various
- 18:37levels of this message.
- 18:38So repos, actors, and interactions, and then parses the message directly into those types.
- 18:45So the final call there is passing in the red message and then specifying the type as a list
- 18:51of interactions, which are tree down into actors and repos.
- 18:54Exactly.
- 18:55So this is what you mentioned earlier about having more function-based.
- 18:58So you just say decode, give it the string or the bytes, and you say type equals list of
- 19:04bracket, top-level class.
- 19:06And just like Pydantic, these can be nested.
- 19:09So there's an interaction, which has an actor.
- 19:10There's an actor class, which has a login, which has a type.
- 19:13So your Pydantic model for how those kind of fit together is pretty straightforward, right?
- 19:19Pretty similar.
- 19:19Yeah.
- 19:20And then you're just programming with classes.
- 19:21Awesome.
- 19:22Yep.
- 19:22And it'll all work well with, like, mypy or Pyright or whatever you're using if you're doing
- 19:26static analysis tools.
- 19:27Yeah.
- 19:27So you've thought about making sure that not just does it work well from a usability perspective,
- 19:32but it, like, the type checkers don't go crazy.
- 19:35Yeah.
- 19:35And any, you know, editor integration you have should just work.
- 19:38Nice.
- 19:39Because there's sometimes, oh gosh, I think maybe FastAPIs changes, but you'll have things
- 19:45like you would say the type of an argument being passed in, if it's, say, coming off the
- 19:50query string, you would say it's depend.
- 19:52It's a type depends, not an int, for example.
- 19:56It's because it's being pulled out of the query string.
- 19:58I think that's FastAPI.
- 19:59And while it makes the runtime happy and the runtime says, oh, I see you want to get this
- 20:04int from the query string, the type checkers and stuff are like, depends.
- 20:09What is this?
- 20:09Like, this is an int.
- 20:10Why are you trying to use this depends as an int?
- 20:12This doesn't make any sense.
- 20:13I think it's a bit of a challenge to have the runtime, the types drive the runtime, but
- 20:17still not freak it out, you know?
- 20:19Yeah.
- 20:19I think that the Python typing ecosystem, especially with the recent changes in new versions and
- 20:25the annotated wrapper, are moving towards a system where these kinds of APIs can be spelled
- 20:30natively in ways that the type checkers will understand.
- 20:33But if your project that existed before these changes, you obviously had some preexisting
- 20:38way to make those work that might not play as nicely.
- 20:41So there's the upgrade cost of the project.
- 20:43I'm not envious of the work that Samuel Covenant team have had to do to upgrade Pydantic to erase
- 20:49some old warts in the API that they found.
- 20:50It's nice to see what they've done and it's impressive.
- 20:52But it's, I have the benefit of starting this project after those changes in typing
- 20:56ecosystem existed.
- 20:57You know, can look at hindsight mistakes others have made and learn from them.
- 21:01Yeah, that's really excellent.
- 21:01They have done, like I said, I'm a big fan of Pydantic and it took them almost a year.
- 21:06I interviewed Samuel about that change and it was no joke.
- 21:09You know, it was a lot of work.
- 21:10But, you know, what they came up with, pretty compatible, pretty much feels like the same
- 21:15Pydantic.
- 21:15But, you know, if you peel back the covers, it's definitely not.
- 21:18All right.
- 21:19So the other interesting thing about Ipmar's article here is the performance side.
- 21:23So it's okay.
- 21:23Do you get fixed memory usage or does it vary based on the size of the data?
- 21:28And do you get schema validation?
- 21:29Right.
- 21:30So standard lib, just straight JSON module, 420 milliseconds.
- 21:35OR JSON, the fast one, a little less than twice as fast, 280 milliseconds.
- 21:39iJSON for iterable JSON.
- 21:42300, so a little more than the fast one.
- 21:45Message spec, 90 milliseconds.
- 21:47That's awesome.
- 21:48That's like three times as fast as the better one.
- 21:51Over four times as fast as the built-in one.
- 21:54It also is doing, you know, quote unquote, more work.
- 21:56It's validating the response as it comes in.
- 21:58Exactly.
- 21:59So you're sure that it's correct then too.
- 22:01All those other ones are just giving you dictionaries and YOLO.
- 22:04Do what you want with them, right?
- 22:06But here you're actually, all those types that you described, right?
- 22:09The interaction and the actors and the repos and the class structure, that's all validation.
- 22:13So in on top of that, you've created classes which are heavier weight than dictionaries because
- 22:18general classes are heavier weight than dictionaries because they have the dunder dict that has
- 22:23all the fields in there effectively anyway, right?
- 22:26That's not true for structs.
- 22:28Structs are slot classes.
- 22:29Yes.
- 22:30Structs.
- 22:30They are a lighter weight to allocate than a dictionary or a standard class.
- 22:34That's one of the reasons they're faster.
- 22:35Yeah.
- 22:35Structs are awesome.
- 22:36And so the other thing I was going to point out is, you know, you've got 40 megabytes
- 22:39of memory usage versus 130.
- 22:41So almost four times less than the standard module.
- 22:45And the only thing that beats you is the iterative one because it literally only has one in memory
- 22:50at a time, right?
- 22:50One element.
- 22:51Yeah.
- 22:52So this benchmark is kind of hiding two things together.
- 22:56So there is the output, what you're parsing.
- 22:59Everything here except for iJSON is going to parse the full input into something.
- 23:03One big batch.
- 23:04It's more efficient than orJSON or the standard lib in this respect because we're only extracting
- 23:08the fields we care about.
- 23:09But you're still going to end up with a list of a bunch of objects.
- 23:11iJSON is only going to pull one in a memory at a time.
- 23:14So it's going to have less in memory there.
- 23:16And then you have the memory usage of the parsers themselves, which can also vary.
- 23:21So orJSON's memory usage in its parser is a lot higher than msgspecs, regardless
- 23:26of the output size.
- 23:27There's a little more internal state.
- 23:29So this is a pretty interesting distinction that you're calling out here.
- 23:33So for example, if people check out this article, which I'll link, there's like tons of stuff
- 23:39that people don't care about in the JSON, like the avatar URL, the gravatar ID, you know,
- 23:45the reference type, whether it's a brand, like this stuff that you just don't care about,
- 23:49right?
- 23:49But to parse it in, you got to read that.
- 23:51But what's pretty cool you're saying is like, in this case, the class that Edmar came up with
- 23:56is just repo driving from struct.
- 23:59It just has a name.
- 23:59There's a bunch of other stuff in there, but you don't care about it.
- 24:02And so what you're saying is like, if you say that that's the decoder, it looks at that
- 24:06and goes, there's a bunch of stuff here.
- 24:07We're not loading that.
- 24:09We're just going to look for the things you've explicitly asked us to model, right?
- 24:13There's no sense in doing the work if you're never going to look at it.
- 24:16A lot of different serialization frameworks.
- 24:18I can't remember how Pydantic responds when you do this, but, you know, the comments beyond
- 24:23Pydantic, so it doesn't really matter, is they'll freak out to say, oh, there's extra
- 24:27stuff here.
- 24:28What am I supposed, you know, for example, this repo, it just has name, but in the data model,
- 24:32it has way more in the JSON data.
- 24:35So you try to deserialize it.
- 24:37It'll go, well, I don't have room to put all this other stuff.
- 24:39Things are, you know, freak out.
- 24:40And this one is just like, no, we're just going to filter down to what you asked for.
- 24:43I really, it's nice in a couple of ways.
- 24:45It's nice from performance, nice from clean code.
- 24:47I don't have to put all those other fields I don't care about, but also from, you talked
- 24:51about the evolution friendliness, right?
- 24:53Because what's way more common is that things git added rather than taken away or changed.
- 24:59It's like, well, the complexity grows.
- 25:01Now repos also have this, you know, related repos or sub repos or whatever the heck they
- 25:06have, right?
- 25:06And this model here will just let you go, whatever, don't care.
- 25:10Yeah.
- 25:10If GitHub updates their API and adds new fields, you're not going to get an error.
- 25:14And if they remove a field, you should get a nice error that says expected, you know,
- 25:19field name, and now it's missing.
- 25:20You can track that down a lot easier than a random key error.
- 25:24I agree.
- 25:24I think, okay, let's, let's dive into the struct a little bit because that's where we're
- 25:28kind of on that now.
- 25:29And I think this is one of the highlights of what you built.
- 25:32Again, it's kind of the same mental model as people are familiar with some data classes
- 25:36with Pydantic and attrs and so on.
- 25:39So when I saw your numbers, I won't come back and talk about benchmarks with numbers.
- 25:43But I just thought like, wow, this is fast.
- 25:45And while the memory usage is low, you must be doing something native.
- 25:49You must be doing something crazy in here.
- 25:51That's not just Dunder slots.
- 25:53While Dunder slots is awesome.
- 25:55There's more to it than that, right?
- 25:57And so they're written in C, quite speedy and lightweight.
- 26:01So measurably faster than data classes, attrs and Pydantic.
- 26:04Like, tell us about these classes.
- 26:06Like, this is, this is pretty interesting.
- 26:07It's mentioned earlier.
- 26:08They're not exactly, but they're, they're basically slots classes.
- 26:11So Python's data model, actually CPython's data model is either a class is a standard class
- 26:16where it stores its attributes in a dict.
- 26:19That's not exactly true.
- 26:20There's been some optimizations where the keys are stored separately alongside the class structure
- 26:25and all the values are stored on the object instances.
- 26:27But in model, there's dict classes and there's slots classes, which you pre-declare your attributes
- 26:32to be in this, this Dunder slots interval.
- 26:35And those get stored in line in the same allocation as the object instance.
- 26:40There's no pointer chasing.
- 26:41What that means is that you can't set extra attributes on them that weren't pre-declared,
- 26:45but also things are a little bit more efficient.
- 26:48We create those automatically when you subclass from a struct type.
- 26:51And we do a bunch of other interesting things that are stored on the type.
- 26:55That is why we had to write a metaclass in C.
- 26:58I went to read it.
- 26:59I'm like, whoa, okay.
- 27:00Maybe we'll come back to this.
- 27:01There's a lot of stuff going on in that type.
- 27:03One of the problems with this hobby project is that I wrote this for fun
- 27:07and a little bit of work related, but mostly fun.
- 27:09And it's not the easiest code base for others to step into.
- 27:12It fits my mental model, not necessarily everyone's.
- 27:15Yeah.
- 27:15I can tell you weren't looking for VC funding because you didn't write it in Rust.
- 27:18Seems to be the common denominator these days.
- 27:22Yeah.
- 27:22Why C?
- 27:23Just because CPython's already in C?
- 27:25And that's the...
- 27:26And I use C.
- 27:27I do know Rust, but for what I wanted to do in the use case I had in mind,
- 27:31I wanted to be able to touch the C API directly.
- 27:34And that felt like the easiest way to go about doing it.
- 27:39This portion of Talk Python To Me is brought to you by Posit, the makers of Shiny, formerly RStudio, and especially Shiny for Python.
- 27:47Let me ask you a question.
- 27:49Are you building awesome things?
- 27:51Of course you are.
- 27:52You're a developer or a data scientist.
- 27:53That's what we do.
- 27:54And you should check out Posit Connect.
- 27:56Posit Connect is a way for you to publish, share, and deploy all the data products that you're building using Python.
- 28:04People ask me the same question all the time.
- 28:07Michael, I have some cool data science project or notebook that I built.
- 28:10How do I share it with my users, stakeholders, teammates?
- 28:13Do I need to learn FastAPI or Flask or maybe Vue or React.js?
- 28:18Hold on now.
- 28:19Those are cool technologies, and I'm sure you'd benefit from them.
- 28:22But maybe stay focused on the data project?
- 28:24Let Posit Connect handle that side of things.
- 28:27With Posit Connect, you can rapidly and securely deploy the things you build in Python.
- 28:31Streamlit, Dash, Shiny, Bokeh, FastAPI, Flask, Quattro, Reports, Dashboards, and APIs.
- 28:38Posit Connect supports all of them.
- 28:40And Posit Connect comes with all the bells and whistles to satisfy IT and other enterprise requirements.
- 28:46Make deployment the easiest step in your workflow with Posit Connect.
- 28:50For a limited time, you can try Posit Connect for free for three months by going to talkpython.fm.posit.
- 28:57That's talkpython.fm.posit.
- 28:59The link is in your podcast player show notes.
- 29:02Thank you to the team at Posit for supporting Talk Python.
- 29:05Okay, so from a consumer of this struct class, I just say class.
- 29:11And your example is user.
- 29:12You say class, user, parentheses, derived from struct.
- 29:14In the field, colon, type.
- 29:16So like name, colon, string, groups, colon, set of, str, and so on.
- 29:20It looks like standard data classes type of stuff.
- 29:23But what you're saying is your meta class goes through and looks at that and says, okay,
- 29:27we're going to create a class called user, but it's going to have slots called name, email,
- 29:31and groups, among other things, right?
- 29:33Like does that magic for us?
- 29:35Yeah.
- 29:35And then it sets up a bunch of internal data structures that are stored on the type.
- 29:39Okay.
- 29:40Give me a sense of like, like, what's something, why do you got to put that in there?
- 29:43What's in there?
- 29:44So the way data classes work, after they do all the type parsing stuff, which we have
- 29:48to do too, they then generate some code and eval it to generate each of the methods.
- 29:54So when you're importing or when you define a new data class, it generates an init method
- 29:59and evals it and then stores it on the instance.
- 30:01That means that you have little bits of bytecode floating around for all of your new methods.
- 30:05msgspec structs instead, each of the standard methods that the implementation provides, which
- 30:10would be, you know, init, wrapper, equality checks, copies, you know, various things are
- 30:16single C functions.
- 30:19And then the type has some data structures on it that we can use to define those.
- 30:25So we have a single init method for all struct types that's used everywhere.
- 30:29And as part of the init method, we need to know the fields that are defined on the struct.
- 30:34So we have some data stored on there about like the field names, default values, various
- 30:38things.
- 30:38Nice.
- 30:38Because they're written in C rather than, you know, Python bytecode, they could be a lot
- 30:42faster.
- 30:43And because we're not having to eval a new method every time we define a struct, importing
- 30:47structs is a lot faster than data classes.
- 30:49Something, I'm not going to guess, I have to look up on my benchmarks, but they are basically
- 30:54as efficient to define as a handwritten class where data classes have a bunch of overhead.
- 30:59If you've ever written a project that has, you know, a hundred of them, importing
- 31:02can slow down.
- 31:03Yeah.
- 31:03Okay.
- 31:03Because you basically are dynamically building them up, right?
- 31:06Yeah.
- 31:06In data class story.
- 31:07Yeah.
- 31:08So you've got kind of the data class stuff.
- 31:10You got, as you said, dunder net, repper, copy, et cetera.
- 31:13But you also have dunder match args for pattern matching.
- 31:16That's pretty cool.
- 31:18And dunder rich repper for pretty printing support with rich.
- 31:21Yeah.
- 31:22If you just rich.print, it'll take that, right?
- 31:24What happens then?
- 31:25It preprints it similar to like how a data class should be rendered.
- 31:28Rich is making a pretty big impact.
- 31:29So rich is special.
- 31:31I enjoy using it.
- 31:32This is excellent.
- 31:33You've got all the stuff generated.
- 31:35So much of it isn't C and super lightweight and fast.
- 31:38But from the way we think of it, it's just a Python class, even a little less weird than
- 31:43data classes, right?
- 31:44Because you don't have to put a decorator on it.
- 31:45You just derive from this thing.
- 31:47So that's super cool.
- 31:48Yeah.
- 31:49Super neat.
- 31:50The hope was that these would feel familiar enough to users coming from data classes or
- 31:54adders or Pydantic or all the various models that learning a new one wouldn't be necessary.
- 32:00They're the same.
- 32:02Excellent.
- 32:02One difference if you're coming from Pydantic is there is no method defined on these by default.
- 32:06So you define a struct with fields A, B, and C. Only A, B, and C exist as attributes on that class.
- 32:13You don't have to worry about any conflicting names.
- 32:14Okay.
- 32:15So for example, like the Pydantic ones have, I can't remember, the V1 versus V2.
- 32:22It's like, I can't remember, like two dictionary effectively, right?
- 32:25Where they'll like dump out the JSON or strings or things like that.
- 32:28In V1, there's a method dot JSON.
- 32:30Yeah, that's right.
- 32:31Which if you have a field name JSON will conflict.
- 32:33They are remedying that by adding a model prefix for everything, which I think is a good idea.
- 32:38I think that's a good way of handling it.
- 32:40Yeah.
- 32:40Yeah.
- 32:40It's like model underscore JSON or dict or something like that.
- 32:43Yeah.
- 32:43Cool.
- 32:43Yeah, that's one of the few breaking changes they actually, unless you're deep down in
- 32:47the guts of Pydantic that you might encounter.
- 32:49Yeah.
- 32:50You don't have to worry about that stuff because you're more function-based, right?
- 32:53You would say decode, or I guess, yeah, decode.
- 32:57Here's some data, some JSON or something.
- 33:00And then the thing you decode it into would be your user type.
- 33:03You'd say type equals user rather than going to the user directly, right?
- 33:07Can we put our own properties and methods and stuff on these classes and that'll work all right?
- 33:12Yeah.
- 33:13To a user, you should think of this as a data class that doesn't use a decorator.
- 33:17Okay.
- 33:17They should be identical unless you're ever trying to touch the dunder data class fields attribute
- 33:23that exists on data classes.
- 33:24There should be no runtime differences as far as you can tell.
- 33:27And when you're doing the schema validation, it sounds like you're basically embracing the
- 33:31optionality of the type system.
- 33:35If you say int, it has to be there.
- 33:36If you say optional int or int pipe none, it may not be there, right?
- 33:40No.
- 33:40It's close.
- 33:41I'm going to be pedantic here a little bit.
- 33:43The optional fields are ones that have default values set.
- 33:46So optional bracket int without a default is still a required field.
- 33:50It's just one that could be an int or none.
- 33:52You'd have to have a literal none passed in.
- 33:53Otherwise, we'd error.
- 33:54This more matches with how mypy interprets the type system.
- 33:57Got it.
- 33:57Okay.
- 33:58So if I had an optional thing, but it had no value, I'd have to explicitly set it to
- 34:02none.
- 34:02Yes.
- 34:03Or would, yeah.
- 34:03Or it'd have to be there in the data every time.
- 34:06Like other things, you have default factories, right?
- 34:09Passing a function that gets called.
- 34:10If it does, I guess if it doesn't exist, right?
- 34:12If the data's in there, it's being deserialized, it won't.
- 34:15Okay.
- 34:15Excellent.
- 34:16And I guess your decorator creates the initializer.
- 34:19But another thing that I saw that you had was you have this post init, which is really nice.
- 34:24Like a way to say like, okay, it's been deserialized.
- 34:26Let me try a little further.
- 34:28Tell us about this.
- 34:29This is cool.
- 34:29Yeah, it's coming from data classes.
- 34:31They have the same method.
- 34:32So if you need to do any extra thing after init, you can use it here rather than trying to override
- 34:37the built-in init, which we don't let you do.
- 34:40Right.
- 34:40Because it has so much magic to do.
- 34:42Like let it do it.
- 34:43And you don't want to override that anyway.
- 34:45You'll have to deal with like passing all the arguments.
- 34:48Yeah, it runs Python instead of maybe C, all these things, right?
- 34:51So post init would exist if you have more complex constraints, right?
- 34:56Currently, that's one reason to use it.
- 34:58We currently don't support custom validation functions.
- 35:01There's no .validate, decorator, various frameworks, different ways of defining these.
- 35:06We have some constraints that are built in.
- 35:07You can constraint the number to be greater than some value, but there's no way to specify
- 35:12custom constraints currently.
- 35:14It's on the roadmap.
- 35:15It's a thing we want to add.
- 35:16Post init's a way to hack around that.
- 35:18So right now, you're looking at the screen.
- 35:20You have a post init defined, and you're checking if low is greater than high, raise an error.
- 35:25And that'll bubble up through decodes and raise an ice user facing validation error.
- 35:29In the long run, we'd like that to be done a little bit more field-based.
- 35:32Somewhere to come from other frameworks.
- 35:34It is tricky, though, because the validation goes onto one field or the other.
- 35:38You don't have composite validators necessarily, right?
- 35:41And so there's totally valid values of this low, but whatever it is, it has to be lower than high.
- 35:47But how do you express that relationship?
- 35:49So I think this is awesome.
- 35:50Other areas where it could be interesting is under some circumstances, maybe you've got to compute some field also that's in there that's not set.
- 35:59I don't know.
- 35:59There's some good options in here.
- 36:00I like it a lot.
- 36:01Yeah, I guess the errors just come out as just straight out of like something went wrong with under post init rather than field low has this problem.
- 36:08It's a little harder to relate an error being raised to a specific field if you raise it in a post init.
- 36:13Yeah.
- 36:13Also, since you're looking at this, and I'm proud that I got this to work, the errors raised in post init use chained exceptions.
- 36:20So you can see a little bit of the cause of where it comes from.
- 36:22And getting those to work at the Python C API is completely undocumented and a little tricky to figure out.
- 36:28It's a lot of reading how the interpreter does it and making me write, you know, 12 incantations to get them to bubble up right.
- 36:34Yeah, I do not envy you working on this struct, this base class.
- 36:38But I mean, that's where part of the magic is, right?
- 36:41And that's why I wanted to dive into this because I think it behaves like Python classes, but it has these really special features that we don't normally get, right?
- 36:49Like low memory usage, high performance, accessing the fields.
- 36:53Is that any quicker or is it like standard struct level quick?
- 36:57Attribute access and settings should be the same as any other class.
- 37:00Things that are faster are init.
- 37:02Reper, not that that should matter.
- 37:04If you're looking for a high performance reper, that's...
- 37:06You're doing it wrong.
- 37:07Seems like you're doing something wrong.
- 37:08Equality checks, comparisons, so sorting, you know, less than, greater than.
- 37:12I think that's it.
- 37:12Everything else should be about the same.
- 37:14So field ordering, you talked about like evolution over time.
- 37:17Does it, does this matter?
- 37:19Field ordering is mostly defining how, what happens if you do subclasses and stuff.
- 37:22This whole section is, if you're not subclassing, shouldn't hopefully be relevant to you.
- 37:27So we match how data class handles things for ordering.
- 37:30Okay.
- 37:30So I could have my user, but I could have a super user that derives from my user that derives
- 37:35from struct and things will still hang together.
- 37:37And so figuring out how all the fields order out through that subclassing is what this doc
- 37:41is about.
- 37:41Yeah.
- 37:42Another type typing system thing you can do a lot is have explicitly claimed something
- 37:46as a class variable.
- 37:47You know, Python is weird about its classes and what makes a variable that's associated
- 37:53with a class and or not.
- 37:55Right.
- 37:56So with these type of classes, you would say like class example colon, and then you have
- 37:59x colon int.
- 38:00Right.
- 38:01And that appears, will appear on the static type, like example.x, but it also imbues each
- 38:06object with its own copy of that x.
- 38:08Right.
- 38:09Which is like a little bit, is it a static thing or part of the type or is it not?
- 38:14It's kind of funky.
- 38:14But you also can say that explicitly from the typing, you say this is a class variable.
- 38:19What happens then?
- 38:20Right.
- 38:20Like, so standard attributes exist on the instances where a class var exists on the class itself.
- 38:26Class fars are accessible on an instance, but the actual data is stored on the class.
- 38:31So you don't have an extra copy.
- 38:33I see.
- 38:33So if there's some kind of singleton type of thing or just one of them.
- 38:37Yeah.
- 38:37Yeah.
- 38:37It has to do with how Python does attribute resolution where it'll check on the instance
- 38:43and then on the type and also there's descriptors in there, you know, somewhere.
- 38:46Interesting.
- 38:47Okay.
- 38:47Like other things, I suppose it's pretty straightforward that you take these types and you use them
- 38:53to validate them.
- 38:53But one of the big differences with msgspec.struct versus pydantic.base model and others is the
- 39:00validation doesn't happen all the time.
- 39:02It just happens on encode decode.
- 39:04Right.
- 39:05Like you could call the constructor and pass in bad data or like it just doesn't pay attention.
- 39:10Right.
- 39:11Yeah.
- 39:11Why is it like that?
- 39:12So this is one of the reasons I wrote my own thing rather than building off of something
- 39:17existing like pydantic.
- 39:18Side tangent here, just to add history context here.
- 39:21Message spec was started about three years ago.
- 39:22The JSON and it kind of fell into its full model about two years ago.
- 39:26So this has existed for around two years.
- 39:27Yeah.
- 39:28We're pre the pydantic rewrite.
- 39:30Anyway, the reason I wanted all of this was when you have your own code, where bugs can
- 39:36come up.
- 39:36Are bugs in your own code?
- 39:37I've typed something wrong.
- 39:39I've made a mistake and I want that to be checked.
- 39:41Or it can be user data that's coming in.
- 39:43Or, you know, maybe it's a distributed system and it's still my own code.
- 39:46It's just a file or database.
- 39:47Yeah.
- 39:47Whatever.
- 39:48Yeah.
- 39:48We have many mechanisms of testing our own code.
- 39:51You can write tests.
- 39:52You have static analysis tools like mypy, Pyright, or checking.
- 39:55It's a lot easier for me to validate that a function I wrote is correct.
- 39:59Got it.
- 39:59There are other tools I believe that we should lean on rather than runtime validation in those
- 40:05cases.
- 40:05But when we're reading in external data, whether it's coming over the wire, coming from a file,
- 40:10coming from user input in some way, we do need to validate because the user could have
- 40:13passed us something that doesn't match our constraints.
- 40:17As soon as you started trusting user input, you're in for a bad time.
- 40:20We don't want to arbitrarily be trusting.
- 40:21We do validate on JSON decoding.
- 40:24We validate on message pack decoding.
- 40:25We also have a couple of functions for doing in-memory conversions.
- 40:28So there's msgspec convert, msgspec to built-ins for going the other way.
- 40:33So that's for doing conversion of runtime data that you got from someone rather than a specific
- 40:37format.
- 40:37Yeah, because if you're calling this constructor and passing the wrong data, mypy should check
- 40:42that.
- 40:42PyCharm should check that.
- 40:44Maybe Ruff would catch it.
- 40:46I'm not sure.
- 40:46But there's a bunch of tools.
- 40:48Yeah, Ruff doesn't have a type checker yet.
- 40:49TBD on that.
- 40:51Yeah, OK.
- 40:52Yeah, being able to check these statically, it means that we don't have to pay the cost
- 40:57every time we're running, which I don't think we should.
- 40:59That's extra runtime performance that we don't need to be spending.
- 41:02Yeah, definitely.
- 41:03Check it on the boundaries, right?
- 41:04Check it where it comes into the system, and then it should be good.
- 41:07The other reason I was against adding runtime validation to these structs is I want all types
- 41:11to be on equal footing.
- 41:12And so if I am creating a list, the list isn't going to be doing any validation because it's
- 41:17the Python built-in.
- 41:18Same with data classes, same with attrs, types, whatever.
- 41:21And so only doing a validation when you construct some object type that subclasses from a built-in
- 41:26that I've defined, or a type I've defined, doesn't give parity across all types and might
- 41:31give a user misconceptions about when something is validated and when they can be sure it's
- 41:35correct first when it hasn't.
- 41:36Yeah.
- 41:37Have you seen bear type?
- 41:38I have.
- 41:39Yeah.
- 41:39Bear type's a pretty interesting option.
- 41:41If people really want runtime validation, they could go in and throw bear type onto their
- 41:46system and let it do its thing.
- 41:48Even if you're not doing it, you should read the docs just for the sheer joy that these
- 41:51docs are.
- 41:52Oh, they are pretty glorious.
- 41:53Yeah, I'll do it.
- 41:54It's kind of like burying the lead a little down here, but they described themselves as
- 41:58bear type brings Rust and C++ inspired zero-cost abstractions into the lawless world of the
- 42:04dynamically typed Python by enforcing type safety at the granular level of functions and methods
- 42:09against type hints standardized by the Python community of O order one, non-amortized worst
- 42:14case time with negligible constant factors.
- 42:17Oh my gosh.
- 42:18So much fun, right?
- 42:20They're just joking around here, but it's a pretty cool library.
- 42:22If you want runtime type checking, it's pretty fast.
- 42:25Okay.
- 42:25Interesting.
- 42:26You talked about the pattern matching.
- 42:28I'll come back to that.
- 42:29One thing I want to talk about.
- 42:30Well, okay.
- 42:31Frozen.
- 42:31Frozen instances.
- 42:32This comes from data classes.
- 42:34Without the instances being frozen, the structs are mutable.
- 42:37Yeah, I can get one, change its value, serialize it back out, things like that.
- 42:42Yep.
- 42:42But frozen, I suppose, means what you would expect, right?
- 42:44Yeah.
- 42:45Frozen has the same meaning as a data class equivalent.
- 42:47How deep does frozen go?
- 42:49So for example, is it frozen all the way down?
- 42:51So in the previous example from Itamar, it had the top level class and then other structs
- 42:57that were nested in there.
- 42:58If I say the top level is frozen, do the nested ones themselves become frozen?
- 43:02No.
- 43:03So frozen applies to the type.
- 43:05So if you define a type as frozen, that means you can't change values that are set as attributes
- 43:10on that type.
- 43:10But you can still change things that are inside it.
- 43:13So if a frozen class contains a list, you can still append stuff to the list.
- 43:16There's no way to get around that except if we were to do some deep, deep, deep magic,
- 43:20which we shouldn't.
- 43:21It would definitely slow it down if you had to go through and recreate frozen lists every
- 43:25time you saw a list and stuff like that.
- 43:27Yeah.
- 43:27Okay.
- 43:27And then there's one about garbage collection in here.
- 43:30Yeah.
- 43:31Which is pretty interesting.
- 43:32There we go.
- 43:33Disabling garbage collection.
- 43:35This is under the advanced category.
- 43:36Warning box around this that tells you not to.
- 43:39What could go wrong?
- 43:40Come on.
- 43:40Part of this was experimenting with the DAS distributed scheduler, which is a unique application,
- 43:46I think, for people that are writing web stuff in that all of its data is kept in memory.
- 43:50There's no backing database that's external.
- 43:52And so it is as fast to respond as the bits of in-memory computation it needs to do before
- 43:58it sends out a new task to a worker.
- 43:59So in this case, their serialization performance matters.
- 44:03But also, it's got a lot of in-memory state.
- 44:05It's a dict of types of lots of chaining down.
- 44:09The way the CPython garbage collector works is that these large dictionaries could add GC overhead.
- 44:15Every time a GC thing happens, it has to scan the entire dictionary.
- 44:19Any container thing could contain another.
- 44:20And once you do that, there could be a cycle.
- 44:22And then for very large graphs, GC pauses could become noticeable.
- 44:27Yes.
- 44:27This is an experiment and seeing ways around that.
- 44:29Because we've done some deep magic with how structs work, we can disable GC for subclasses,
- 44:34user-defined types, which CPython does not expose normally and really isn't something you
- 44:40probably want to be doing in most cases.
- 44:42But if you do, you get a couple benefits.
- 44:44The types are smaller.
- 44:45Every instance needs to include some extra state for tracking GC.
- 44:49I believe on recent builds, it's 16 bytes.
- 44:52So it's two pointers.
- 44:53So that's, you know, you're saving 16 bytes print.
- 44:56That's non-trivial.
- 44:56Yeah.
- 44:57If you got a huge list of them, that could be a lot.
- 44:59Yeah.
- 44:59And two, they don't, they're not traced.
- 45:02And so if you have a lot of them, that's reducing reduction in tracing overhead every time
- 45:07a GC pass happens.
- 45:08GC puts more overhead on top of stuff than you would think.
- 45:12So I did some crazy GC stuff over at Talk Python and training with my courses.
- 45:16You go to slash sitemap.xml.
- 45:19I don't know how many entries are in the sitemap, but there are 30,000 lines of sitemap.
- 45:24Like many, many, many, many, many, many thousands of URLs up to come back with details.
- 45:29Just to generate that page in one request with the default Python settings in Python 3.10,
- 45:35I think it was, it was doing 77 garbage collections while generating this page.
- 45:40That's not ideal.
- 45:43I switched it to just change or tweak how frequently the GC runs.
- 45:46So like every 70,000, no, every 50,000 allocations instead of every 700.
- 45:51And the site runs 20% faster now and uses the same amount of memory, right?
- 45:55And so this is not exactly what you're talking about here, but it's in the, it plays in the
- 46:00same space as like, you can dramatically change the things that are triggering this and dramatically
- 46:05change the performance potentially.
- 46:08The caveat is you better not have cycles.
- 46:10Yeah.
- 46:11So the other thing with these is, as you pointed out, is the indicator of when a GC pass happens
- 46:16has to do with how many GC aware types have been allocated.
- 46:19Yep.
- 46:19And so if your market type is not a GC type, then the counter is an increment.
- 46:22You're not paying that cost.
- 46:23Right.
- 46:24You can allocate all the integers you want all day long.
- 46:26It'll never affect the GC.
- 46:27But if you start allocating classes, dictionaries, tuples, et cetera, that is like, well, those
- 46:31could contain cycles.
- 46:32You have 700 more than you've deallocated since last time.
- 46:35I'm going to go check it.
- 46:36One place this comes up is if you have, say, a really, really large JSON file.
- 46:41Because any deserialization is an alien allocation heavy workload, which means that you can have
- 46:46a GC pause happen, you know, several times during it because you've allocated, you know,
- 46:50that many types.
- 46:51Turning up GC for these types lets you avoid those GC pauses, which gives you actual runtime
- 46:56benefits.
- 46:56A different way of doing this that is less insane is to just disable GC during the decode.
- 47:01Do a, you know, GC disable, JSON decode, GC enable, and you only do a GC pass once.
- 47:07Especially because JSON as a tree-like structure can never create cycles.
- 47:10You're not going to be having an issue there.
- 47:12But you're probably allocating a lot of different things that are container types.
- 47:15And so it looks to the GC like, oh, this is some really sketchy stuff.
- 47:20We better get on the game here.
- 47:21But you know, as you said, there's no cycles in JSON.
- 47:25So there's a lot of scenarios like that, like database queries.
- 47:29You know, I got a thousand records back from a table.
- 47:31They're all some kind of container.
- 47:33So minimum one GC happens just to read back that data.
- 47:36But you know, there's no cycles.
- 47:38So why is the GC happening?
- 47:39You can kind of control that a little bit.
- 47:41Or you just turn the number up to 50,000 like I did.
- 47:43It still happens, but less.
- 47:46A lot less.
- 47:46Yeah.
- 47:47So this is pretty interesting, though, that you just set GC equals false.
- 47:50Where do you set this?
- 47:51Is this like in the derived bit?
- 47:54It's part of the class definition.
- 47:56So we make use of class definition keyword arguments.
- 48:00So it goes after the struct type in the subclass.
- 48:03You do, you know, my class, open over at the C, struct, comma, GC equals false, close, comma,
- 48:08colon, rest of the class.
- 48:10Yeah, that's where I thought.
- 48:11But it is a little funky.
- 48:12Yeah.
- 48:13I mean, it kind of highlights the meta class action going on there, right?
- 48:16What else should people know about these structs?
- 48:18They're fast and they can be used for not just serialization.
- 48:21So if you are just writing a program and you happen to have msgspec on your system,
- 48:25it should be faster to use them than data classes.
- 48:27Whether that matters is, of course, application dependent.
- 48:30But they're like generally a good idea.
- 48:32They happen to live in this serialization library, but that's just because that's where I wrote
- 48:35them.
- 48:36Yeah, that's where they.
- 48:37In a future world, we might split them out into a sub package.
- 48:39Yeah.
- 48:40Fast struck.
- 48:41Pippin saw fast struck.
- 48:42Who knows?
- 48:43Yet to be named.
- 48:45So better than data classes.
- 48:47I mean, they have the capabilities of data classes.
- 48:48So that's cool.
- 48:49But better than straight up regular classes, like Bayer classes, you know, class colon name.
- 48:54Are opinionated a little bit.
- 48:56They're how I think people probably should be writing classes.
- 48:59And they're opinionated in a bit.
- 49:00That means that you can't write them in ways that I don't want you to.
- 49:03So the way a struct works is you define attributes on it using type annotations.
- 49:07And we generate a fast init method for you.
- 49:09We don't let you write your own init.
- 49:11In the subclass, you can't override init.
- 49:13The generated one is the one you get.
- 49:15That means that like if you're trying to create an instance from something that isn't those field
- 49:19names, you can't do that.
- 49:21You need to use a new class method for writing those.
- 49:23I believe this is how people, at least on projects I work on, generally use classes.
- 49:27So I think it's a fine limitation.
- 49:29But it is putting some guardrails around how the arbitrariness of how you can define a Python
- 49:35class.
- 49:35You could have a, you know, a handwritten class that has two attributes, X and Y, and your
- 49:40init takes, you know, parameters A and B.
- 49:43Sure.
- 49:43Or maybe it just takes X and it always defaults Y unless you go and change it after or whatever,
- 49:48right?
- 49:48I guess you could do sort of do that with default values, right?
- 49:51But you couldn't prohibit it from being passed in.
- 49:53I'm feeling some factory classes.
- 49:55The attrs docs have a whole, whole page telling people about why this pattern is, is better
- 50:01and nudging them to do this.
- 50:02So this isn't a new idea.
- 50:03Yeah.
- 50:03Go check out attrs and see what they're saying as well.
- 50:06There's probably a debate in the issues somewhere on GitHub.
- 50:08There always is a debate.
- 50:10Yeah.
- 50:10Let's see.
- 50:10Let's go get a bunch of stuff up here I want to talk about.
- 50:12I guess really quickly, since there's a lot of like C native platform stuff, right?
- 50:17This is available on, you know, pip install msgspec.
- 50:21We're getting a wheel.
- 50:22It seemed like it worked fine on my M2 MacBook Air.
- 50:26Like what are the platforms that I get a wheel that don't have to worry about compiling?
- 50:30So we use CI BuildWheel for building everything.
- 50:33And I believe I've disabled some of the platforms.
- 50:36The ones that are disabled are mostly disabled because CI takes time.
- 50:40I need to minimize them.
- 50:42But everything common should exist, including Raspberry Pi and various ARM builds.
- 50:46Excellent.
- 50:47Okay.
- 50:47Yeah.
- 50:47It seemed like it worked just fine.
- 50:49I didn't really know that it was like doing a lot of native code stuff, but it seems like
- 50:53it.
- 50:53And also available on Conda, Conda Forge.
- 50:55So that's cool.
- 50:56If you Conda, you can also just Conda install it.
- 50:59Kind of promised talking about the benchmarks a little bit, didn't I?
- 51:02So benchmarks are always...
- 51:04If you click on the graph on the bottom, it'll bring you to it.
- 51:06Yeah.
- 51:06They're always rife with like, that's not my benchmark.
- 51:10I'm doing it different, you know?
- 51:11But give us a sense of just...
- 51:13It says fast, italicies leaning forward.
- 51:16Give us a sense of like, where does this land?
- 51:18Is it, you know, 20% faster or is it a lot better?
- 51:21Yeah.
- 51:21So as you said, benchmarks are a problem.
- 51:22The top of this benchmark docs is a whole argument against believing them and telling you to run
- 51:27your own.
- 51:27So take a grain of salt.
- 51:29I started benchmarking this mostly just to know how we stacked up.
- 51:33It's important if you're making changes to know if you're getting slower.
- 51:35It's also important to know what the actual trade-offs of your library are.
- 51:38All software engineering is trade-offs.
- 51:40So msgspec is generally fast.
- 51:43The JSON parser in it is one of the fastest in Python or the fastest, depending on what
- 51:50your message structure is and how you're invoking it.
- 51:52It at least is on par with or JSON, which is generally what people consider to be the fast
- 51:56parser.
- 51:57Right.
- 51:57That's where they go when they want fast.
- 51:59Yeah.
- 51:59Yes.
- 51:59If you are specifying types, so if you, you know, add in a type annotation to a JSON decode
- 52:05call with msgspec, even if you're decoding the whole message, you're not doing
- 52:08a subset.
- 52:08We're about 2x faster than our JSON.
- 52:10You actually get a speed up by defining your types because struct types are so efficient
- 52:15to allocate versus a deck.
- 52:17That's kind of the opposite of what you might expect, right?
- 52:19It seems like we're doing more work, but we're actually able to do less because we can
- 52:23take some more, you know, efficient fast paths.
- 52:25And then a thousand objects with validation compared to.
- 52:29Yeah.
- 52:29Mesher, Murrow, Seatters, Pydantic, and so on.
- 52:34Probably the last one.
- 52:34This was a grab bag of various validation libraries that seemed popular.
- 52:38Mashemar is the one that DBT uses.
- 52:40I think they're the primary consumer of that.
- 52:42Catters is for attrs.
- 52:43Pydantic is, you know, ubiquitous.
- 52:45This right here in this benchmark graph we're looking at is against Pydantic V1.
- 52:50I have not had a chance to update our benchmarks to go against V2.
- 52:54There's a separate gist somewhere that has got some numbers there.
- 52:57Standard number they throw out is like 22 times faster.
- 53:00So it still puts you multiples faster.
- 53:02In that benchmark, we're averaging 10 to 20x faster than Pydantic V2.
- 53:06In numbers I run against V1, we're about 80 to 150x faster.
- 53:11So it really is structure dependent.
- 53:13Yeah, sure.
- 53:14Do you have one field or do you have a whole bunch of stuff?
- 53:17Yeah, exactly.
- 53:17And what types of fields?
- 53:19To be getting more into the weeds here, JSON parsing is not easy.
- 53:24Message pack parsing is like the format was designed for computers to handle it.
- 53:27It's, you know.
- 53:28Seven bytes in there is an integer here.
- 53:30Yeah, okay.
- 53:31Where JSON is human readable and parsing strings into stuff is slow.
- 53:35Right.
- 53:35The flexibility equals slowness, yeah.
- 53:37Our string parsing routines in msgspec are faster than the ones used by orJSON.
- 53:43Our integer parsing routines are slower.
- 53:46But there's a different trade-off there.
- 53:47Interesting.
- 53:48Okay.
- 53:48Yeah, I think this is, it just seems so neat.
- 53:50There's so much flexibility, right, with all the different formats.
- 53:53And the restrictions on the class, they exist, but they're unstruck.
- 53:56But they're not insane, right?
- 53:58I mean, you build proper OOP type of things.
- 54:02You don't need super crazy hierarchies.
- 54:04Like, that's where you get in trouble with that stuff anyway.
- 54:06So don't do it.
- 54:07I guess we don't have much time left.
- 54:09One thing I think we could talk about a bit maybe would be, I find it, the extensions.
- 54:13Just maybe talk about parsing stuff that is kind of unknown.
- 54:16This is pretty interesting.
- 54:17So the way we allow extension currently, there's an intention to change this and expand it.
- 54:23But currently, extending adding new types is done via a number of different hooks.
- 54:28They're called when a new type is encountered.
- 54:30So custom user defined type of some form.
- 54:32I liked doing this rather than adding it into the annotation because if I have a new type, I want it to exist probably everywhere.
- 54:38And I don't want to have to keep adding in and use the serializer and deserializer as part of the type annotations.
- 54:45So to define a new type that you want to encode, you can add an encode hook, which takes in the instance and returns something that msgspec knows how to handle.
- 54:54This is similar to, you know, if you're coming from standard library JSON, there's a default callback.
- 54:59It's the same.
- 54:59We renamed it to be a little better name in my mind, but it's the same thing.
- 55:02Right.
- 55:03So your example here is taking a complex number, but storing it as a tuple of real and imaginary numbers, but then pulling it back into a proper complex number object.
- 55:12Super straightforward.
- 55:13Yeah.
- 55:13But makes it possible.
- 55:14Yeah.
- 55:15Yeah.
- 55:15That's really cool.
- 55:16So people can apply this.
- 55:17And this, I guess, didn't really matter on the output destination, does it?
- 55:21Your job here is to take a type that's not serializable to one that is, and then whether that goes to a message pack or JSON or whatever is kind of not your problem.
- 55:31Yeah.
- 55:31And then the decode hook is the inverse.
- 55:32You get a bunch of stuff that is, you know, core types, ints, strings, whatever, and you compose them up into your new custom type.
- 55:39Jim, I think we're getting about out of time here.
- 55:41But I just want to point out, like, if people hit the user guide, there's a lot of cool stuff here.
- 55:44And there's a whole performance tips section that people can check out.
- 55:50You know, if we had more time, maybe we'd go into them.
- 55:52But, like, for example, you can call msgspec dot JSON dot encode, or you can create an encoder and say the type and stuff and then reuse that.
- 55:59Right.
- 55:59Those kinds of things.
- 56:01Yeah.
- 56:01There's another method that is, again, a terrible internal hack for reusing buffers.
- 56:07So you don't have to keep allocating byte buffers every message.
- 56:09You can allocate a byte array once and use it for everything.
- 56:12Save some memory.
- 56:13Let me ask, Ellie's got a question.
- 56:14I'm going to read some words that don't mean anything to me, but they've made to you.
- 56:17How does the performance of message pack plus msgspec with the array-like equals true optimization compared to flat buffers?
- 56:25So by default, objects, so struct types, data classes, whatever, encode as objects in the stream.
- 56:31So a JSON object has keys and values, right?
- 56:34If you have a point with fields X and Y, it's got X and Y, you know, one, two.
- 56:39We have an array-like optimization, which lets you drop the field names.
- 56:42And so that would instead include as an array of, you know, one comma two, dropping the X and Y.
- 56:47Reduces the message size on the wire.
- 56:48If the other side knows what the structure is, it can, you know, pull that back up into a type.
- 56:53In terms of message pack as a format, plus with the array-like optimization, the output size should be approximately the same as you would expect it to come out of flat buffers.
- 57:03The Python flat buffers library is not efficient for creating objects from the binary.
- 57:09So it's going to be a lot faster to pull it in.
- 57:11Obviously, this is then a very custom format.
- 57:13You're doing a weird thing.
- 57:15And so compatibility with other ecosystems will be slower.
- 57:18Or it's not slower necessarily, but you'll have to write them yourself.
- 57:21Yeah.
- 57:21Not everything knows how to read the message pack.
- 57:23More brittle, potentially.
- 57:24Yeah.
- 57:25Yes.
- 57:25Yeah.
- 57:25But for Python, talking to Python, that's probably the fastest way to go between processes.
- 57:29And probably a lot faster than JSON or YAML or something like that.
- 57:33Okay.
- 57:33Excellent.
- 57:34I guess, you know, there's many more things to discuss, but we're going to leave it here.
- 57:38Thanks for being on the show.
- 57:39Final call to action.
- 57:40People want to get started with message pack.
- 57:43Are you accepting PRs if they want to contribute?
- 57:45What do you tell them?
- 57:47First, I encourage people to try it out.
- 57:48I'm available, you know, to answer questions on GitHub and stuff.
- 57:51It is obviously a hobby project.
- 57:53So, you know, if the usage bandwidth increases significantly, we'll have to get some more
- 57:58maintainers on and hopefully we can make this more maintainable over time.
- 58:01But once the sponsor funds exceed $10,000, $20,000, $30,000 a month, like you'll reevaluate
- 58:06your...
- 58:07No, just kidding.
- 58:07Sure.
- 58:08Sure.
- 58:08But yeah, please try it out.
- 58:10Things work, should be hopefully faster than what you're currently using and hopefully intuitive
- 58:15to use.
- 58:15We've done a lot of work to make sure the API is friendly.
- 58:17Yeah.
- 58:17It looks pretty easy to get started with.
- 58:19The docs are really good.
- 58:20No, thank you.
- 58:21Congrats on the cool project.
- 58:22Thanks for taking the time to come on the show and tell everyone about it.
- 58:25Thanks.
- 58:25Yeah.
- 58:26See you later.
- 58:26Bye.
- 58:27This has been another episode of Talk Python To Me.
- 58:29Thank you to our sponsors.
- 58:31Be sure to check out what they're offering.
- 58:33It really helps support the show.
- 58:35This episode is sponsored by Posit Connect from the makers of Shiny.
- 58:39Publish, share, and deploy all of your data projects that you're creating using Python.
- 58:44Streamlit, dash, dash, dash, dash, dash, dashboards, dashboards, dashboards, and APIs.
- 58:50Posit Connect supports all of them.
- 58:52Try Posit Connect for free by going to talkpython.fm/posit.
- 58:57P-O-S-T.
- 58:58Want to level up your Python?
- 59:00We have one of the largest catalogs of Python video courses over at Talk Python.
- 59:04Our content ranges from true beginners to deeply advanced topics like memory and async.
- 59:09And best of all, there's not a subscription in sight.
- 59:12Check it out for yourself at training.talkpython.fm.
- 59:15Be sure to subscribe to the show.
- 59:17Open your favorite podcast app and search for Python.
- 59:20We should be right at the top.
- 59:21You can also find the iTunes feed at /itunes, the Google Play feed at /play,
- 59:26and the direct RSS feed at /rss on talkpython.fm.
- 59:30We're live streaming most of our recordings these days.
- 59:33If you want to be part of the show and have your comments featured on the air,
- 59:37be sure to subscribe to our YouTube channel at talkpython.fm/youtube.
- 59:41This is your host, Michael Kennedy.
- 59:43Thanks so much for listening.
- 59:45I really appreciate it.
- 59:46Now get out there and write some Python code.
- 59:48Thank you.