pythonpython-typing

How can I use type hints to declare an instance method of a class accepts another class instance as a parameter?


How can I write a class in Python that has a method with an argument that should be an instance of the class?

class MyClass:
    def compare(self, other: MyClass):
        pass

This gives me an error:

NameError: name 'MyClass' is not defined

Solution

  • Try using annotations package, described here.

    Change your code to the following:

    from __future__ import annotations
    
    class MyClass:
        def compare(self, other: MyClass):
            pass
    

    Also, there is a helpful tutorial here.