【问题标题】:Pydantic: allow mutation, forbid to change typesPydantic:允许突变,禁止改变类型
【发布时间】:2021-04-19 18:33:36
【问题描述】:

有什么方法可以禁止改变变异 Pydantic 模型的类型?例如,

from pydantic import BaseModel

class AppConfig(BaseModel):

    class Config:
        allow_mutation = True
    
    a: int = 33
    b: float = 22.0

我希望能够更改字段,例如:

config = AppConfig()
config.a = 44

但我想禁止更改字段的类型,例如:

config.a = '44'
<Some error message here>

【问题讨论】:

    标签: python types pydantic


    【解决方案1】:

    理解 Pydantic 的一个关键点是它会尝试强制到你注释的类型。例如。它会尝试在您为a 提供的任何输入上调用int。如果您想要这种行为,请使用strict types

    In [1]: from pydantic import BaseModel, StrictInt, StrictFloat
       ...:
       ...: class AppConfig(BaseModel):
       ...:
       ...:     class Config:
       ...:         allow_mutation = True
       ...:
       ...:     a: StrictInt = 33
       ...:     b: StrictFloat = 22.0
       ...:
    
    In [2]: AppConfig(a=42, b=0.0)
    Out[2]: AppConfig(a=42, b=0.0)
    
    In [3]: AppConfig(a='42', b=0.0)
    ---------------------------------------------------------------------------
    ValidationError                           Traceback (most recent call last)
    <ipython-input-3-702f4ffeef8d> in <module>
    ----> 1 AppConfig(a='42', b=0.0)
    
    ~/opt/miniconda3/envs/wrangle/lib/python3.7/site-packages/pydantic/main.cpython-37m-darwin.so in pydantic.main.BaseModel.__init__()
    
    ValidationError: 1 validation error for AppConfig
    a
      value is not a valid integer (type=type_error.integer)
    

    此外,默认情况下,pydantic 不会对属性的分配执行验证,要更改您需要在 Config 中设置 validate_assignment 的行为,因此您需要:

    In [1]: from pydantic import BaseModel, StrictInt, StrictFloat
       ...:
       ...: class AppConfig(BaseModel):
       ...:
       ...:     class Config:
       ...:         allow_mutation = True
       ...:         validate_assignment = True
       ...:
       ...:     a: StrictInt = 33
       ...:     b: StrictFloat = 22.0
       ...:
    
    In [2]: config = AppConfig()
    
    In [3]: config
    Out[3]: AppConfig(a=33, b=22.0)
    
    In [4]: config.a = '42'
    ---------------------------------------------------------------------------
    ValidationError                           Traceback (most recent call last)
    <ipython-input-4-39b2a238b39e> in <module>
    ----> 1 config.a = '42'
    
    ~/opt/miniconda3/envs/wrangle/lib/python3.7/site-packages/pydantic/main.cpython-37m-darwin.so in pydantic.main.BaseModel.__setattr__()
    
    ValidationError: 1 validation error for AppConfig
    a
      value is not a valid integer (type=type_error.integer)
    

    【讨论】:

      猜你喜欢
      • 2022-12-10
      • 1970-01-01
      • 2017-12-26
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 2015-02-24
      • 2011-02-02
      相关资源
      最近更新 更多