Search code examples
pythontype-hinting

Python raises a NameError when using a type hint in arguments of class method


Take a look at this code:

class Test:
    def __eq__(self, rhs: Test):
        # ...
        pass

The code fails with the following output:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    class Test:
  File "test.py", line 2, in Test
    def __eq__(self, rhs: Test):
NameError: name 'Test' is not defined

How do I use a type hint of a class in the class method arguments itself?


Solution

  • Because Test is not defined yet, you will need to do a forward declaration like this:

    class Test:
        def __eq__(self, rhs: "Test"):
            # ...
            pass