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
Exclude private attributes (PrivateAttr
) from dataclass constructor
#9234
Comments
PrivateAttr
PrivateAttr
) from dataclass constructor
Thanks for the proposal here. I think a better route forward would probably be to emit a warning in this case, not to disallow it entirely. I think disallowing would have to wait for a major release. Feel free to open a PR adding the |
Thanks for your answer, @sydney-runkle 😊 I've dug further into it, and it seems that besides the fact that pydantic allows private attributes in the To be clearer, I'm using vscode, together with the Python (v2024.4.1), Pylance (v2024.4.1) and Ruff (v2024.16.0) extensions. As you can see, it's clearly much more verbose and confusing than the actual signature generated by pydantic (which is clear and correct). So, while we can implement the |
@sydney-runkle After some more research, I think I've found a solution that's both backward-compatible and satisfies the type-checking needs. So, to let the type checkers know that
According to the definition of runtime behavior of I made a draft PR #9293 that applies my proposed changes. I think more work regarding the added |
Hello, I just encountered the same bug, but using Also in favor of making it throwing an exception: the usage of a signature different from the documentation provided by the IDE (and intended interface) creates inconsistency. |
Hi @idan22moral, Thanks for looking into this with backwards compatibility in mind! Will take a look at your PR here shortly. Curious to hear what @Viicos thinks about this approach, he seemed quite informed about all things |
Initial Checks
Description
I came across #9192 while trying to find a clue as to why private attributes (
PrivateAttr
) are not excluded from the (BaseModel) constructor, just like how fields (Field
) are excluded when settinginit=False
.The documentation states that private attributes:
So, in a slightly better world, when I have this class:
instantiation of
Person
in this form (with private attributes as parameters) should not be allowed:My proposal is to simply remove the private attributes from the parameters passed to the
__init__
function.If there is a concern for backward-compatibility (assuming that users send value to private attributes in the constructor even though these values are ignored), the same concept from #8552 can be applied (adding
init=False
flag).Though I think this is a not-so-good idea and the change should break compatibility in favor of better interface and less unclear behavior.
Example Code
No response
Python, Pydantic & OS Version
The text was updated successfully, but these errors were encountered: