r/Python • u/uh_sorry_i_dont_know • Apr 21 '24
Discussion Should I use pydantic for all my classes?
Pydantic makes your code safer by making it strongly typed. You can no longer input a wrongly typed argument without getting an error (if pydantic can't convert it). This is great but to me it seems that sometimes standard python classes still seem preferable.
Perhaps it's because I'm not using it correctly but my code for a pydantic class is much longer then for a normal class. Especially if you are working with computed attributes. Then you have to start using special decorators and for every computed attribute you have to declare a function with "def ..." Instead of in an init function just being able to write attribute_3 = attribute 1 + attribute 2.
So I'm just wondering are you using pydantic for all your classes? And how do you handle computed fields in pydantic especially upon instantiation I find it hard to implement.
204
u/twitch_and_shock Apr 21 '24
No, I don't. I only use pydantic to validate user input, such as when building an web API. The user might send some json data, and I use a pydantic class to validate that the data received contains all the required arguments with the correct types.
When coding things that are for my use or my colleagues use, I use type hints but not pydantic.
112
u/alexmojaki Apr 21 '24
No.
I'm working at Pydantic, the company. Samuel Colvin is my boss. We're working on a commercial product that should go public soon.
Many of the classes in our codebase are pydantic models, but most are not. There's more dataclasses than pydantic models, and there's also plain standard classes.
34
u/ePaint Apr 21 '24
Pydantic for JSON data received from outside, dataclasses for everything else
47
u/FloxaY Apr 21 '24
Use it when you actually need to verify the data, "wrongly typed argument" sounds like something you can avoid and should be catched by a static type checker. Don't add unnecessary overhead and external dependecies to your project.
20
u/SBennett13 Apr 21 '24
I like msgspec for message deserialization and type validation. Most of the time Pydantic is overkill. Msgspec is fast and the Struct classes work well.
I don’t do many web things, so it might not be as ideal for web validation.
17
u/deep_mind_ Apr 21 '24
No. Pydantic is for user input validation -- it's just needless overhead for internal classes.
7
u/YnkDK Apr 21 '24
People say "only for user input".
Does that mean:
24
u/ArgetDota Apr 21 '24
No, you should use beartype (or other similar libraries) if you just want runtime type checking. They are especially built for this purpose, while pydantic is more data-oriented.
https://github.com/beartype/beartype
12
u/nekokattt Apr 21 '24 edited Apr 21 '24
Pydantic doesn't make your code any more strongly typed than dataclasses do. Its just a library to handle more complex serialization and validation concerns.
If you want to "enforce" strong typing as a first principle, use a programming language that refuses to run if typechecking fails.
Typehints in Python are an advice, not a contract. You can attempt to enforce them by using additional linters but if strong typing is your core concern, then I'd say you are using the wrong tool for the job, or you are expecting some level of safety from an issue that you are not actually addressing.
Before I get downvoted here for the above... using MyPy provides no more of a constraint for strong typing at runtime than black provides a strong constraint of consistent formatting at runtime.
Static typing in Python compliments the maintainability of the code, it does not decide if the code is valid.
The overhead argument can be met with "performance isn't everything" and that may be true, but if it is the difference between doubling how much you pay for cloud infrastructure in 9 months time because you've added so much overhead to internal processing that you need beefier VPS instances, maybe save yourself the rewrite. Follow best and common practises first and foremost.
TL;DR use the right tool for the right job. Validation and parsing? Sure. Internal models? There is zero benefit of the overhead. Use named tuples and/or dataclasses based on what you need. For internal service to service communication, using something like protobuf will be beneficial as a contract.
9
u/tacosandspicymargs Apr 21 '24
Learn what statically and strongly typed actually mean. Use mypy —strict, and more static analysis tooling in general. Maybe learn another language to help fill some of the gaps in your programming fundamentals - people who learn to code in python typically miss out on some basic but important concepts and form bad habits.
15
u/ambidextrousalpaca Apr 21 '24
The Python interpreter will let you go as far as altering the behaviour of the
+operator at runtime, so don't trick yourself into thinking that some library will let you turn your Python code into Rust. If you want to use a typed language then do so: there are plenty of options. If not, then embrace Python for what it's good at and be thankful that you never have to spend hours battling to get a compiler to run a perfectly acceptable script.3
u/yvrelna Apr 21 '24
No you shouldn't.
The only classes that should be Pydantic are classes that models user inputs and sometimes it might be beneficial want model the program output and API calls as well, but these are much rarer cases and should be used sparingly.
3
u/LankyOccasion8447 Apr 21 '24
You can use data classes if you want to do typing
3
u/erez27 import inspect Apr 21 '24 edited Apr 21 '24
I use a different variation of
dataclassprovided by runtype, but it's essentially the same idea.For computed attributes, I usually define the computed attribute as a property, or I use
__post_init__.Try to keep it simple. And if you can't keep it simple, then just use a normal
__init__. I do so for about 5% of my classes.5
u/-Buzzy- Apr 21 '24
Good post, I am looking forward to reading the discussion in the comments.
5
u/ProsodySpeaks Apr 21 '24
I use it a lot, but I'm often integrating tools that use it, like Fastapi, sqlmodel, or combadge.
Pydantic-settings is also super cool btw.
Has anyone done any benchmarking to see if there's much of an overhead?
2
u/Cybasura Apr 22 '24
I did at one point want to give pydantic a try, but since python 3.9 iirc python have added static typing using the ":" notation, like the following
Granted, if you have default values then you cant define it but this looks pretty decent
So I didnt bother getting into pydantic since now I have explicit type definitions now
2
u/E-woke Apr 24 '24
I only use Pydantic to validate inputs that are highly prone to type errors
2
u/Living-Leather232 Sep 09 '24
Pydantic can sometimes make your code safer by making it strongly typed
FTFY
1
u/PolyglotTV Apr 21 '24
Super easy to add computed fields with
attrs. The field factory can takeselfas an argument.1
u/Slight-Living-8098 Apr 21 '24
Not all of them, only in things I need to verify returns what it supposed to return.
If you're wanting a stronger typed Python, Mojo is coming along nicely.
1
u/pudds Apr 21 '24
If I don't need to map to or from JSON, I generally use a dataclass because they are lighter.
1
u/rover_G Apr 21 '24
Use in place of dataclasses to validate incoming data from clients and in some cases to revalidate data before sending it to an external service.
1
u/I_will_delete_myself Apr 21 '24
No. If you want a Python that acts like static typed.
a. Use MyPy with type hints.
b. Use another programming language that actually is static typed to begin with. I suggest C++ or Rust so you can create bindings.
You don't ask a bird to climb a tree like a monkey, when supposed to fly there instead. Use the right tool for the job.
1
u/Black-DVD-Archiver Apr 22 '24
I use asserts for every method and function argument parameter. I check the dataclass types in _post_init and I very seldom have typing issues as a mistake almost always throws an error. type hinting all the way as well
1
u/s_basu Apr 25 '24
Dataclass if you need to hold a bunch of related data together in a record type structure and transfer it around (data-transfer-objects) Pydantic if you need data serialization / deserialization and/or DTOs. Normal classes for anything else.
0
u/gerardwx Apr 21 '24
No.
0
u/zanfar Apr 22 '24
IMO, this is not a generally desirable feature. I never want my code to do something I didn't explicitly mean.
Pydantic does this because it's designed to accept outside input. Its design goal is input validation, but that's not a general goal.
I want to be notified if the argument is the wrong type; period. I also want to know before people are using my code, not at runtime. All that is the purpose of a static type checker, and it can be implemented with even less effort than Pydantic.
-1
u/ibite-books Apr 21 '24
mypy
-1
u/ReflectedImage Apr 21 '24
Well making stuff strongly typed usually increases bugs. Is there a reason you want your code to have more bugs?
If you want to reduce bugs you move from static typing to duck typing and move from OOP style to functional style. See Clojure the most defect free commercial programming language.
For why this is the case, you have removed an uncommon bug class and in exchange massively complicated your entire code base. It's a bad trade-off.
-2
u/HiT3Kvoyivoda Apr 21 '24
Isn’t there already a strongly typed python superset?