File: computed_field.py

package info (click to toggle)
pydantic 2.12.5-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,640 kB
  • sloc: python: 75,984; javascript: 181; makefile: 115; sh: 38
file content (26 lines) | stat: -rw-r--r-- 799 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from functools import cached_property

from pydantic import BaseModel, computed_field


class Square(BaseModel):
    side: float

    # mypy limitation, see:
    # https://mypy.readthedocs.io/en/stable/error_code_list.html#decorator-preceding-property-not-supported-prop-decorator
    @computed_field  # type: ignore[prop-decorator]
    @property
    def area(self) -> float:
        return self.side**2

    @computed_field  # type: ignore[prop-decorator]
    @cached_property
    def area_cached(self) -> float:
        return self.side**2


sq = Square(side=10)
y = 12.4 + sq.area
z = 'x' + sq.area  # type: ignore[operator]  # pyright: ignore[reportOperatorIssue]
y_cached = 12.4 + sq.area_cached
z_cached = 'x' + sq.area_cached  # type: ignore[operator]  # pyright: ignore[reportOperatorIssue]