-1

Trying to create a python class which require another instance of the same class for some methods, but I get a NameError.

Here is a quick example :

class test(object):
    def met(self,other:test):
        pass

when parsing this python raise a NameError, this error comes from the fact that for python the name test still doesn't exist while parsing his methods (or at least the methods header).

My question is : how to avoid this NameError while keeping the obligation for the type of other in the function header(ie not using an isinstance like function in the method).

Mike Slinn
  • 7,705
  • 5
  • 51
  • 85
Galyfray
  • 118
  • 1
  • 10

1 Answers1

1

Enclose forward references to types defined later in quotes, like this:

class test(object):
    def met(self,other:'test'):
        pass

This is explained in PEP484

Mike Slinn
  • 7,705
  • 5
  • 51
  • 85