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
Private fields in python use dunder prefix, not __name__ pattern #4833
Comments
Thanks @rafalkrupinski for reporting this issue. |
@hramezani yes, also that it encourages code practice against the standards |
Seems a good idea. |
I'd argue, having support for The issue might be lying in naming of It's also not quite clear to me what exactly this issue is suggesting. @rafalkrupinski, do you have preferred outcome and a way of achieving it? I personally think, One thing for sure, though: it's definitelly not a bug, but rather a design choice, and it's stated in docs:
|
Initially I wanted to set a default version when creating the data object. class DataTransfer(BaseModel)
__default_version = "1.0"
version: str = __default_version
# other data...
container = DataTransfer(mydata=...) # sets version to __default_version Of course it's a bad code, bc it also set up default version when reading external data. And the private variable doesn't need any annotations, except perhaps Cheers |
@rafalkrupinski According to Pydantic v2 docs on private model attributes: "Private attribute names must start with underscore to prevent conflicts with model fields. However, dunder names (such as attr) are not supported." This implies that Pydantic will recognize an attribute with any number of leading underscores as a private one. Indeed, looking in the test in this PR #7265 the behavior of an attribute with double leading underscores is exactly as expected. It behave similarly to an attribute with a single leading underscore and it behaves like a regular Python private attribute to which the name mangling ('m._Model__foo' instead of |
Initial Checks
Description
pydantic.PrivateAttr expects that the field is either prefixed with a single underscore (sunder) or surrounded with double underscores, like __name__.
Following https://peps.python.org/pep-0008/#descriptive-naming-styles
Example Code
No response
Python, Pydantic & OS Version
Affected Components
.dict()
and.json()
construct()
, pickling, private attributes, ORM modeThe text was updated successfully, but these errors were encountered: