python 如何在pydantic中忽略字段repr?

rvpgvaaj  于 2023-06-04  发布在  Python
关注(0)|答案(2)|浏览(185)

当我想使用属性库忽略一些字段时,我可以使用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这样的选项吗?

7y4bm7vi

7y4bm7vi1#

看起来这个特性已经在不久前实现了requestedalso
但是,它似乎还没有进入最新版本。
我看到两个选项如何启用该功能无论如何:

1.使用功能请求中提供的解决方法

定义一个helper类:

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'
xqkwcwgp

xqkwcwgp2#

现在已实施:

import typing

from pydantic import BaseModel, Field
from pydantic.typing import Annotated

class Temp(BaseModel):
    foo: typing.Any
    boo: Annotated[typing.Any, Field(repr=False)]

参见:https://docs.pydantic.dev/latest/usage/schema/#field-customization

相关问题