New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add a round_float validator #8903
Comments
These both seem like reasonable feature requests, and I believe they'll require some work in |
Hi, I'd like to contribute on this issue (as my first contribution). Still trying to understand the whole architecture of the pydantic project. |
Awesome! Hmm, yeah we'll have to decide on exactly what we want the API to look like regarding the rounding behavior. Before we do that, @Zac-HD, do you think there's any place for some sort of rounding annotation in |
Let's start with just Pydantic, and then we can move it to annotated-types if there's wider demand for it and consensus on the semantics 🙂 It would be very difficult for e.g. pschanely/CrossHair#201 to support float rounding. |
How do you want to proceed about deciding what the API should look like? Maybe I can make propositions if you point me to relevant chunks of codes to compare the issue with. |
Ah, apologies for the delay, this notification got buried in my email. Why don't we start with an implementation that uses Python's I think the |
Sorry for the delay, I will make a proposition this week. |
Sorry I'm a bit late to the party, but regarding
from pydantic import AfterValidator
def round_to(ndigits: int, /) -> AfterValidator:
return AfterValidator(lambda v: round(v, ndigits))
class Model(BaseModel):
my_field: Annotated[float, round_to(2)] What I'm mostly worried about is if this is added to the |
I don't feel like I can give on informed opinion on the matter. @sydney-runkle maybe you could help me on this? |
Yes, certainly! I'll review your PR and the above comments today! |
Initial Checks
Description
We have a couple of use cases in our code base where we have a pydantic model with a float field, which we want to be rounded. We have an implementation that looks something like:
This is okay but we need to repeat the validator on each model which becomes annoying. We then came up with:
Which works well, however again we still need to have this boiler plate in our code, both defining the function and adding an after validator to each field. It would be amazing if this could be done within pydantic itself.. We noticed that there is the
decimal_places
option in fields however this only seems to be useable forDecimal
instances. Would it be possible to:I imagine for 2 it would look like:
Affected Components
.model_dump()
and.model_dump_json()
model_construct()
, pickling, private attributes, ORM modeThe text was updated successfully, but these errors were encountered: