0

I am trying to use more typing in my code to improve it's readability and safety. Presently, I am trying to do this on an equality overriding method:

class X:
    def __init__(self, t):
        self._t = t

    def __eq__(self, other: X):
        return self._t == other._t

This seems straight forward, however I get an error:

NameError: name 'X' is not defined.

Does python not allow this type of type reference? If so, how can I fix it?

anthony sottile
  • 61,815
  • 15
  • 148
  • 207
CL40
  • 579
  • 1
  • 5
  • 12
  • That's not the right annotation (or implementation) anyway; `__eq__` is supposed to take arbitrary arguments and return `NotImplemented` if it doesn't recognize whatever's on the other side. – user2357112 Sep 30 '19 at 00:31
  • @user2357112 ah that is far more clear. Thank you – CL40 Sep 30 '19 at 00:33
  • 1
    Possible duplicate of [How do I specify that the return type of a method is the same as the class itself?](https://stackoverflow.com/questions/33533148/how-do-i-specify-that-the-return-type-of-a-method-is-the-same-as-the-class-itsel) – Georgy Sep 30 '19 at 08:27

1 Answers1

0

It is possible to annotate it like:

class X:
    def __init__(self, t):
        self._t = t

    def func(self, other: "X"):
        return self._t == other._t

But as user2357112 has said, if you use it on the __eq__ function, mypy will tell you:

a.py:5: error: Argument 1 of "__eq__" incompatible with supertype "object"
a.py:5: note: It is recommended for "__eq__" to work with arbitrary objects, for example:
a.py:5: note:     def __eq__(self, other: object) -> bool:
a.py:5: note:         if not isinstance(other, X):
a.py:5: note:             return NotImplemented
a.py:5: note:         return <logic to compare two X instances>
Sraw
  • 18,892
  • 11
  • 54
  • 87