Automatically mark an attrribute as private #2471
Replies: 3 comments 2 replies
-
Hi @MVrachev from pydantic import BaseModel
class M(BaseModel):
x: str
y: int
_private_x: str
_private_y: int = 2
class Config:
underscore_attrs_are_private = True
m = M(x='q', y=1)
assert not hasattr(m, '_private_x')
m._private_x = 'w'
assert hasattr(m, '_private_x')
assert m._private_x == 'w'
assert m._private_y == 2 Hope it helps! |
Beta Was this translation helpful? Give feedback.
-
Yes, but this still requires me to create a Why not enable this by default when you can't have a public attribute with a name starting with an underscore? |
Beta Was this translation helpful? Give feedback.
-
To avoid backwards compatibility problem in minor releases. I guess we could change it in v2. Any reason not to @PrettyWood? |
Beta Was this translation helpful? Give feedback.
-
Hi, I am wondering why there is the need to explicitly mark certain fields as
PrivateAttr
whenit's forbidden to use underscore as a prefix for a normal field name:
#1476 (comment)
Can't
pydantic
automatically mark the attributes starting with an underscore asPrivateAttr
without the need of specifically marking them as private?This way users will easily name their attributes without wondering what names are allowed and when to use
PrivateAttr
.Beta Was this translation helpful? Give feedback.
All reactions