【问题标题】:How to ignore field repr in pydantic?如何忽略pydantic中的字段repr?
【发布时间】:2021-10-16 10:48:15
【问题描述】:

当我想使用 attr 库忽略某些字段时,我可以使用 repr=False 选项。
但我在 pydantic 中找不到类似的选项

请看示例代码

import typing
import attr

from pydantic import BaseModel


@attr.s(auto_attribs=True)
class AttrTemp:
    foo: typing.Any
    boo: typing.Any = attr.ib(repr=False)


class Temp(BaseModel):
    foo: typing.Any
    boo: typing.Any  # I don't want to print

    class Config:
        frozen = True


a = Temp(
    foo="test",
    boo="test",
)
b = AttrTemp(foo="test", boo="test")
print(a)  # foo='test' boo='test'
print(b)  # AttrTemp(foo='test')

不过不代表完全没有选项,我可以使用print(a.dict(exclude={"boo"}))语法

pydantic 没有像repr=False 这样的选项吗?

【问题讨论】:

    标签: python python-3.x pydantic python-attrs


    【解决方案1】:

    这个功能好像是requestedalsoimplemented不久前。

    但是,它似乎还没有进入latest release

    我看到了两个如何启用该功能的选项:

    1.使用feature request

    中提供的解决方法

    定义一个辅助类:

    import typing
    from pydantic import BaseModel, Field
    
    class ReducedRepresentation:
        def __repr_args__(self: BaseModel) -> "ReprArgs":
            return [
                (key, value)
                for key, value in self.__dict__.items()
                if self.__fields__[key].field_info.extra.get("repr", True)
            ]
    

    并在您的 Model 定义中使用它:

    class Temp(ReducedRepresentation, BaseModel):
        foo: typing.Any
        boo: typing.Any = Field(..., repr=False)
    
        class Config:
            frozen = True
    
    a = Temp(
        foo="test",
        boo="test",
    )
    print(a) 
    # foo='test'
    

    2。 pip install最新master

    我建议在虚拟环境中执行此操作。这对我有用:

    卸载现有版本:

    $ pip uninstall pydantic
    ...
    

    安装最新的master:

    $ pip install git+https://github.com/samuelcolvin/pydantic.git@master
    ...
    

    之后,repr 参数应该开箱即用:

    import typing
    from pydantic import BaseModel, Field
    
    class Temp(BaseModel):
        foo: typing.Any
        boo: typing.Any = Field(..., repr=False)
    
        class Config:
            frozen = True
    
    a = Temp(
        foo="test",
        boo="test",
    )
    print(a) 
    # foo='test'
    

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 2020-08-14
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多