From c532e8324e0a68fcecb239b02d66b55df7d9c684 Mon Sep 17 00:00:00 2001 From: Hyun Sol Date: Mon, 20 Dec 2021 01:08:26 +0900 Subject: [PATCH] #3234 exclude extra field when represent model (#3241) * exclude extra field when represent model * add test code * fix W293 * add change md * Update changes/3234-cocolman.md Co-authored-by: Samuel Colvin * Update pydantic/main.py Co-authored-by: Samuel Colvin * Update tests/test_main.py Co-authored-by: Samuel Colvin Co-authored-by: Samuel Colvin --- changes/3234-cocolman.md | 1 + pydantic/main.py | 4 +++- tests/test_main.py | 10 ++++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 changes/3234-cocolman.md diff --git a/changes/3234-cocolman.md b/changes/3234-cocolman.md new file mode 100644 index 0000000000..b7f9cad68f --- /dev/null +++ b/changes/3234-cocolman.md @@ -0,0 +1 @@ +Fix display of `extra` fields with model `__repr__` diff --git a/pydantic/main.py b/pydantic/main.py index 99d97008b1..fa501701f7 100644 --- a/pydantic/main.py +++ b/pydantic/main.py @@ -873,7 +873,9 @@ def __eq__(self, other: Any) -> bool: return self.dict() == other def __repr_args__(self) -> 'ReprArgs': - return [(k, v) for k, v in self.__dict__.items() if self.__fields__[k].field_info.repr] + return [ + (k, v) for k, v in self.__dict__.items() if k not in self.__fields__ or self.__fields__[k].field_info.repr + ] _is_base_model_class_defined = True diff --git a/tests/test_main.py b/tests/test_main.py index 688cca127d..71da72544b 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -208,6 +208,16 @@ class Config: assert Model(a='10.2', b=12).dict() == {'a': 10.2, 'b': 12} +def test_allow_extra_repr(): + class Model(BaseModel): + a: float = ... + + class Config: + extra = Extra.allow + + assert str(Model(a='10.2', b=12)) == 'a=10.2 b=12' + + def test_forbidden_extra_success(): class ForbiddenExtra(BaseModel): foo = 'whatever'