Skip to content

Add an option in Config to choose which fields to use in __repr_args__ #1831

@Lotram

Description

@Lotram

I may have missed something, but it seems there is no way to exclude a field from an object's representation

Feature Request

I think it would be nice to have an option in Config to choose which fields to use in __repr_args__.

Another solution would be to include an repr boolean in the Field class, exactly like in dataclasses. I don't find it as convenient as the other solution, but maybe it makes more sense, since it's a per-field option.

Why

I have multiple big models ( more than 10 fields) and I'd like to reduce the size of their representation (either when using str() or repr()
So I could override the BaseModel to do something like this:

from typing import List, Optional

from pydantic import BaseModel


class Model(BaseModel):
   def __repr_args__(self):
       if self.Config._fields_in_repr is None:
           return super().__repr_args__()

       return (
           (key, value)
           for key, value in super().__repr_args__()
           if key in self.Config._fields_in_repr
       )

   class Config:
       _fields_in_repr: Optional[List[str]] = None


class User(Model):
   id: int
   login: str
   bio: str
   # lot of other fields

   class Config:
       _fields_in_repr = ["id", "login"]

user = User(id=1, login="Lotram", bio="This could be a rather long description, I don't want it in the the repr")
repr(user) #  "User(id=1, login='Lotram')"

However, IMHO we almost always want to exclude some fields from the object's repr, and I feel like this is generic enough to justify a new option in the BaseConfig class.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions