A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/pydantic/pydantic/issues/415 below:

Validator on dataclasses · Issue #415 · pydantic/pydantic · GitHub

Feature Request

Validator on dataclasses

I recently stumble upon the need for validator on dataclasses, and had a look at the doc, which specify to create an issue for it, so here I am :-)

Here is my usecase :

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import annotations

from pydantic import validator
from pydantic.dataclasses import dataclass
import typing
import mpmath

class PydanticConfig:
    arbitrary_types_allowed = True


class BoundedPriceError(Exception):
    pass


@dataclass(frozen=True, config=PydanticConfig)
class BoundedPrice:
    """
    Class representing a price interval
    """
    value: mpmath.mp.mpf
    # delegating implementation to mpmath
    bounds: mpmath.iv.mpf

    @validator('value')
    def value_init(self, v: float):
        return mpmath.mp.mpf(v)

    @validator('bounds')
    def bounds_init(self, i: typing.Iterable):
        return mpmath.iv.mpf(i)

    def __post_init__(self):
        # checking bounds right after init, to except early.
        self()

    def __call__(self) -> mpmath.mp.mpf:
        """
        Calling this instance verify the bounds and return the actual value
        :return:
        """
        try:
            self.value in self.bounds
        except Exception as exc:
            raise BoundedPriceError("Price value not inside bounds", original=exc)
        return self.value


if __name__ == "__main__":

    p = BoundedPrice(value=34.56, bounds=[33.5, 35.7])
    assert type(p) is BoundedPrice
    print(p)

I had to specifically allow arbitrary types, given how mpmath does his types dynamically (based on the context).
Then I want to use the constructors from mpmath, to rely on its implementation there, and validate the values based on that.

I use a dataclass mostly because it is a convenient way to hold data, and provide useful functions out of the box, and I could eventually extend this dataclass to support basic arithmetic...


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4