简体   繁体   English

如何忽略pydantic中的字段repr?

[英]How to ignore field repr in pydantic?

When I want to ignore some fields using attr library, I can use repr=False option.当我想使用 attr 库忽略某些字段时,我可以使用repr=False选项。
But I cloud't find a similar option in pydantic但是我在 pydantic 中找不到类似的选项

Please see example code请看示例代码

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

However, it does not mean that there are no options at all, I can use the syntax print(a.dict(exclude={"boo"}))但是,这并不意味着根本没有选项,我可以使用语法print(a.dict(exclude={"boo"}))

Doesn't pydantic have an option like repr=False ? pydantic 没有像repr=False这样的选项吗?

It looks like this feature has been requested and also implemented not long ago.看起来此功能已被请求并不久前也已实现

However, it seems like it hasn't made it into the latest release yet.但是,它似乎还没有进入最新版本

I see two options how to enable the feature anyway:我看到两个选项如何启用该功能:

1. Use the workaround provided in the feature request 1. 使用功能请求中提供的解决方法

Define a helper class:定义一个辅助类:

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)
        ]

and use it in your Model definition:并在您的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 the latest master pip install最新的master

I would suggest doing this in a virtual environment.我建议在虚拟环境中执行此操作。 This is what worked for me:这对我有用:

Uninstall the existing version:卸载现有版本:

$ pip uninstall pydantic
...

Install latest master :安装最新的master

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

After that the repr argument should work out of the box:之后, 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM