We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Talks - Sebastian Buczyński: Having fun with pydantic and pattern matching
Learn how to combine Pydantic and pattern matching in Python to validate and handle complex data structures safely, with practical tips for type validation and flow control.
-
Pattern matching with
match/case
in Python is more powerful than simple switch statements, allowing matching on types and attributes -
Order of cases in pattern matching is significant - similar to exception handling, more specific patterns should come before general ones
-
Pydantic models provide schema validation and type checking for data structures, helping handle complex nested data more safely
-
Using Pydantic’s Type Adapter and Union types can replace explicit pattern matching while providing better validation
-
functools.singledispatch
offers an alternative approach for handling different types of events, allowing handler registration based on type -
When handling event streams, it’s important to handle unexpected/malformed messages gracefully through validation and error handling
-
Combining Pydantic with pattern matching allows for both type validation and flow control, but be careful about duplicating logic
-
Union discriminants in Pydantic 2 can simplify handling different message types by looking at type fields automatically
-
Complex nested data structures should be broken down into specialized types rather than handling everything in one large pattern match
-
Consider performance implications - pattern matching implementations may have overhead compared to simpler approaches