[Python-Dev] cpython: inspect: Micro-optimize __eq__ for Signature, Parameter and BoundArguments

Serhiy Storchaka storchaka at gmail.com
Fri May 15 08:07:05 CEST 2015


On 15.05.15 01:23, yury.selivanov wrote:
> https://hg.python.org/cpython/rev/f0b10980b19e
> changeset:   96056:f0b10980b19e
> parent:      96054:15701e89d710
> user:        Yury Selivanov <yselivanov at sprymix.com>
> date:        Thu May 14 18:20:01 2015 -0400
> summary:
>    inspect: Micro-optimize __eq__ for Signature, Parameter and BoundArguments
>
> Provide __ne__ method for consistency.
>
> files:
>    Lib/inspect.py |  32 ++++++++++++++++++++++----------
>    1 files changed, 22 insertions(+), 10 deletions(-)
>
>
> diff --git a/Lib/inspect.py b/Lib/inspect.py
> --- a/Lib/inspect.py
> +++ b/Lib/inspect.py
> @@ -2353,11 +2353,15 @@
>           return hash((self.name, self.kind, self.annotation, self.default))
>
>       def __eq__(self, other):
> -        return (issubclass(other.__class__, Parameter) and
> -                self._name == other._name and
> -                self._kind == other._kind and
> -                self._default == other._default and
> -                self._annotation == other._annotation)
> +        return (self is other or
> +                    (issubclass(other.__class__, Parameter) and
> +                     self._name == other._name and
> +                     self._kind == other._kind and
> +                     self._default == other._default and
> +                     self._annotation == other._annotation))

It would be better to return NotImplemented if other is not an instance 
of Parameter.

         if self is other:
             return True
         if not isinstance(other, Parameter):
             return NotImplemented
         return (self._name == other._name and
                 self._kind == other._kind and
                 self._default == other._default and
                 self._annotation == other._annotation)

And why you use issubclass() instead of isinstance()?

> +    def __ne__(self, other):
> +        return not self.__eq__(other)

This is not need (and incorrect if __eq__ returns NotImplemented). The 
default __ne__ implementations calls __eq__ and correctly handles 
NotImplemented.




More information about the Python-Dev mailing list