Skip to content

Introduce a allow_mutation Field constraint #2195

@sblack-usu

Description

@sblack-usu

Checks

  • I added a descriptive title to this issue
  • I have searched (google, github) for similar issues and couldn't find anything
  • I have read and followed the docs and still think this feature/change is needed
  • After submitting this, I commit to one of:
    • Look through open issues and helped at least one other person
    • Hit the "watch" button on this repo to receive notifications and I commit to help at least 2 people that ask questions in the future
    • Implement a Pull Request for a confirmed bug

Feature Request

I found mentions of a readOnly parameter on the deprecated Schema class but it was not carried over to Field. Others are using validators to enforce readonly on assignment, but it's a common enough feature that pydantic could provide it natively. I am not able to use validators to create a readonly Field because I have validators that need to be run on initialization.

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.7.2
            pydantic compiled: False
                 install path: /Users/scootna/projects/pydantic/pydantic
               python version: 3.8.2 (default, Sep 24 2020, 19:37:08)  [Clang 12.0.0 (clang-1200.0.32.21)]
                     platform: macOS-10.15.7-x86_64-i386-64bit
     optional deps. installed: ['typing-extensions', 'email-validator', 'devtools']
from pydantic import BaseModel, Field

class Entry(BaseModel):
    id: float = Field(allow_mutation=False)
    val: float

    class Config:
        validate_assignment = True

r = Entry(id=1, val=100)
r.id = 2 # raise error when assigning to read_only field

...

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions