0

I am trying to use type checking in Python but am running into an issue on what type of parameter should be used when referring to self.

class MyClass:
  def my_func(self: TYPE?) -> str:
    return 'Hello world!' 

What I am guessing is that it should be of type MyClass but I am not sure about this.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
SomeDutchGuy
  • 2,249
  • 4
  • 16
  • 42
  • 1
    Strictly speaking, the type of `self` can't be know statically, as it depends on the MRO of the run-time type of `self`. – chepner Jan 27 '21 at 21:00
  • Does this answer your question? [How do I type hint a method with the type of the enclosing class and update that with inheritance?](https://stackoverflow.com/questions/65729161/how-do-i-type-hint-a-method-with-the-type-of-the-enclosing-class-and-update-that) – MisterMiyagi Jan 28 '21 at 14:32

1 Answers1

1

You can put the type in quotations to refer to it self (i.e. refer to the class via a string).

class MyClass:
    def my_func(self: 'MyClass') -> str:
        return 'Hello world!'

However, it's not necessary to use type annotation in this case as the self parameter is passed implicitly and is therefore known.

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50