Skip to content
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

Ignore private, leading _ variables when validate_assignment=True #1151

Closed
maxnoe opened this issue Jan 6, 2020 · 2 comments
Closed

Ignore private, leading _ variables when validate_assignment=True #1151

maxnoe opened this issue Jan 6, 2020 · 2 comments

Comments

@maxnoe
Copy link

maxnoe commented Jan 6, 2020

Feature Request

We'd like to configure public (no leading _) variables using pydantic with validate_assignment but still would like private variables _ to be possible, e.g. for logging:

import pydantic
import logging


class ModelWithLog(pydantic.BaseModel):
    option: int = 10

    class Config:
        validate_assignment = True

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._log = logging.getLogger(self.__class__.__name__)  # This fails


m = ModelWithLog()
m.option = 'foo'  # this should fail
m.optoin = 10     # typo, this should fail as well

Result:

Traceback (most recent call last):
  File "model_log.py", line 15, in <module>
    m = ModelWithLog()
  File "model_log.py", line 12, in __init__
    self._log = logging.getLogger(self.__class__.__name__)  # This fails
  File "pydantic/main.py", line 281, in pydantic.main.BaseModel.__setattr__
ValueError: "ModelWithLog" object has no field "_log"```
@samuelcolvin
Copy link
Member

samuelcolvin commented Jan 6, 2020

duplicate of #655 I'm afraid, please comment there.

@maxnoe
Copy link
Author

maxnoe commented Jan 6, 2020

Ah, sorry did not find this issue somehow.

RajatRajdeep pushed a commit to RajatRajdeep/pydantic that referenced this issue May 14, 2024
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants