On Fri, Sep 10, 2021 at 12:28 AM Randolf Scholz
<randolf.sch...@gmail.com> wrote:
>
> Hey,
>
> I noticed that writing a class with a classmethod `__eq__`, it does not work 
> as expected:
>
> ```python
> class ANY:
>     @classmethod
>     def __eq__(cls, other):
>         return True
>
> assert ANY == 2   # succeeds
> assert ANY == 2   # fails
> ```
>
> This is, to my understanding, because `ANY == 2`  translates into 
> `type(ANY).__eq__(2)`.
> However, I think it would be useful to allow user implementation of 
> `classmethod` dunder methods that work as expected, or at least put a big 
> disclaimer in the documentation. I am not sure how difficult this would be to 
> do, but I imagine that `type` could check if the given object/class has a 
> classmethod __eq__ and if so use it as a replacement for `type(obj).__eq__`
>

Yeah, a classmethod doesn't work like that. What you want is a
metaclass, which allows you to change the class of the class itself:

class AnyMeta(type):
    def __eq__(self, other):
        return True

class ANY(metaclass=AnyMeta): pass

assert ANY == 2

Although at this point, you probably don't want a metaclass at all, as
an instance will suffice:

class AnyType:
    def __eq__(self, other):
        return True

ANY = AnyType()
del AnyType # optional

assert ANY == 2

Under what circumstances do you actually want the same handler for
both the class and its instances? Seems unusual. But if you do, a
metaclass will let you do exactly that.

ChrisA
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/IOFMLYGQPXHUNNBQSU2QOA5ZBSYWU3JC/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to