How to store references to objects in pydantic models, not copies #2929
Answered
by
PrettyWood
theRealSuperMario
asked this question in
Question
-
Hi, I make a quick example to illustrate my point: import pydantic
from dataclasses import dataclass
from pydantic import BaseModel
"""When using BaseModel as base class for Point, changes are not forwarded to Point"""
class Point(BaseModel):
x: float
y: float
z: float
def __init__(self, x, y, z) -> None:
super().__init__(x=x, y=y, z=z)
@dataclass
class Line1:
start: Point
end: Point
@pydantic.dataclasses.dataclass
class Line2:
start: Point
end: Point
start1 = Point(0, 0, 0)
end1 = Point(1, 0, 0)
start2 = Point(0, 0, 0)
end2 = Point(1, 0, 0)
line1 = Line1(start1, end1)
line1.start.x += 1
assert line1.start.x == 1
assert start1.x == 1
line2 = Line2(start2, end2)
line2.start.x += 1
assert line2.start.x == 1
assert start2.x == 1 import pydantic
from dataclasses import dataclass
from pydantic import BaseModel
"""When using dataclass as base class for Point, changes ARE forwarded to Point"""
@pydantic.dataclasses.dataclass
class Point:
x: float
y: float
z: float
@dataclass
class Line1:
start: Point
end: Point
@pydantic.dataclasses.dataclass
class Line2:
start: Point
end: Point
start1 = Point(0, 0, 0)
end1 = Point(1, 0, 0)
start2 = Point(0, 0, 0)
end2 = Point(1, 0, 0)
line1 = Line1(start1, end1)
line1.start.x += 1
assert line1.start.x == 1
assert start1.x == 1
line2 = Line2(start2, end2)
line2.start.x += 1
assert line2.start.x == 1
assert start2.x == 1 I was just wondering:
Thanks guys. Cheers 🍺 |
Beta Was this translation helpful? Give feedback.
Answered by
PrettyWood
Jun 18, 2021
Replies: 1 comment 2 replies
-
Hi @theRealSuperMario class Point(BaseModel):
x: float
y: float
z: float
def __init__(self, x, y, z) -> None:
super().__init__(x=x, y=y, z=z)
class Config:
copy_on_model_validation = False Hope it helps! |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
PrettyWood
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @theRealSuperMario
Have you checked
Config.copy_on_model_validation
? :)Hope it helps!