4

I decided that static typing would really make my life easier in Python, considering I normally work in C. I made a class like so:

class node(object):
    """
    properties, constructor, etc.
    """

    def add_outneighbor(self, neighbor: node) -> None:
        """
        do stuff
        """

Flake8 tells me that node is an unknown type in add_outneighbor's definition. Currently I'm working around the issue with isinstance(arg, type), but that seems to defeat the purpose of having the type hints. Is there a better way to do this? This is the resource I referred to in order to get the information on type hints, but I couldn't find any discussion about this self-referential issue.

PyroAVR
  • 719
  • 1
  • 8
  • 19
  • Note that even with type-hints, the interpreter won't necessarily stop you (or raise an error) if a "wrong" type was used. Type-hints are only beneficial to the programmer. – TrebledJ Dec 09 '18 at 18:42
  • That's true, I'm aware of that - I'm using it for myself when debugging and developing, since it would be nice to be able to ensure that my types are correct without having to step through my program to find out I made a typo. – PyroAVR Dec 09 '18 at 18:44
  • 1
    `def add_outneighbor(self, neighbor: 'node') -> None:` node is not yet known because you are inside it - use it's name as string instead – Patrick Artner Dec 09 '18 at 18:48
  • That works! Python sure does have some strange, unorthodox ways of doing things. Thank you! – PyroAVR Dec 09 '18 at 18:51
  • 1
    Possible duplicate of [How do I specify that the return type of a method is the same as the class itself in python?](https://stackoverflow.com/questions/33533148/how-do-i-specify-that-the-return-type-of-a-method-is-the-same-as-the-class-itsel) – Michael0x2a Dec 10 '18 at 18:48

2 Answers2

9

The reason why the interpreter tells you that node is an unknown type is because node must be defined before you can use it in an annotation unless you are using Python 4.

I suggest inserting the following statement: from __future__ import annotations, which will store annotations as strings automatically. Then you won't have that problem again

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
2

The special Self type annotation was introduced in python 3.11. Here are the docs.

An example of its use from the docs:

from typing import Self

class Foo:
   def return_self(self) -> Self:
      return self

An example using the original question:

from typing import Self

class node(object):
    """
    properties, constructor, etc.
    """

    def add_outneighbor(self, neighbor: Self) -> None:
        """
        do stuff
        """
        pass
  • 2
    This is a really old question by now but I'm glad to see that Python has a real answer for this finally! When I first asked this question, I took all annotations as strings to use them for an init-time type checker. The horror! – PyroAVR Feb 14 '23 at 05:09