4

When I want to ignore some fields using attr library, I can use repr=False option.
But I cloud't find a similar option in 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"}))

Doesn't pydantic have an option like repr=False?

Atralupus
  • 131
  • 1
  • 7

2 Answers2

8

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

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:

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

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:

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

After that the repr argument should work out of the box:

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'
insolor
  • 424
  • 8
  • 16
Paul P
  • 3,346
  • 2
  • 12
  • 26
1

This is now implemented:

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

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

zzz
  • 2,515
  • 4
  • 28
  • 38