Python reciprocal type-hinting custom class (definition order issue)

Viewed 39

In python 3.10 I want to define two classes in the same file where one of the methods of each class has to type hint to the other(code follows).

class Foo:
    def some_method(arg: Bar):
        return 'Hello'

class Bar:
    def some_method(arg: Foo):
        return 'World'

Since one has to be defined first the hint is not allowed since the other type has not yet been defined. How can I solve or go around this issue?

1 Answers

You can use quotes to refer the class that have not defined yet like this:

class Foo:
    def some_method(self, arg: 'Bar'):
        return 'Hello'

class Bar:
    def some_method(self, arg: Foo):
        return 'World'
Related