From 36d5663945680720d40c9202b6f36f4852ad92b7 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Fri, 24 Jan 2025 06:46:52 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Speed=20up=20method=20`Rep?= =?UTF-8?q?resentation.=5F=5Frepr=5Fargs=5F=5F`=20by=2031%=20To=20optimize?= =?UTF-8?q?=20the=20`Representation`=20class=20method=20`=5F=5Frepr=5Fargs?= =?UTF-8?q?=5F=5F`=20for=20improved=20performance,=20we=20can=20make=20the?= =?UTF-8?q?=20following=20changes.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. **Avoid using intermediate lists**. - Instead of using a generator to create a tuple and then converting it into a list, we can directly filter and create the list using a generator expression. 2. **Use dictionary access more efficiently**. - We use `.items()` method of the dictionary directly if `__dict__` is available, instead of using `.keys()` and then `getattr`. Here's the optimized code. ### What was changed. 1. **Efficient `__slots__` check**. - Check if `__slots__` is empty and branch directly whether to use `__dict__` or `__slots__`. 2. **Dictionary Access Optimization**. - Use `self.__dict__.items()` directly for name-value pairs, avoiding the need to get keys and fetch values individually. By condensing list creation steps, we reduce overhead and unnecessary iterations, making the function more efficient. --- pydantic/_internal/_repr.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/pydantic/_internal/_repr.py b/pydantic/_internal/_repr.py index 83cb4cc7dfa..588f08c02db 100644 --- a/pydantic/_internal/_repr.py +++ b/pydantic/_internal/_repr.py @@ -42,11 +42,12 @@ def __repr_args__(self) -> ReprArgs: * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]` * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]` """ - attrs_names = self.__slots__ - if not attrs_names and hasattr(self, '__dict__'): - attrs_names = self.__dict__.keys() - attrs = ((s, getattr(self, s)) for s in attrs_names) - return [(a, v) for a, v in attrs if v is not None] + if not self.__slots__: + if hasattr(self, '__dict__'): + return [(k, v) for k, v in self.__dict__.items() if v is not None] + return [] + + return [(s, getattr(self, s)) for s in self.__slots__ if getattr(self, s) is not None] def __repr_name__(self) -> str: """Name of the instance's class, used in __repr__."""