Search code examples
pythonpycharmpython-typing

Typing hints PyCharm for a class used within itself


How do I properly type a class within itself? In PyCharm I am currently getting this error:

enter image description here

This is an unresolved reference error. This normally makes sense because I wouldn't expect PyCharm to support types perfectly. However, when I use it in other classes besides the Item class itself there is no error:

enter image description here

Thus I believe that the error only appears when the type hint is supplied within its own class. So I don't know what exactly to do to prevent this error or if I am using types wrong in general and a type shouldn't be used within itself.

Basically the behavior I am trying to emulate is that you have a crafting recipe for an item and can create new instances of that item with the recipe function.


Solution

  • When using a class as a type inside that class, or anywhere where that type is not fully defined yet, you need to enclose the type in single or double quotes in your annotations:

    class Item:
        ...
        def craft(self, substrates: List['Item'], amount: int) -> List['Item']:
            ...
    

    Sources:

    https://www.python.org/dev/peps/pep-0484/#forward-references

    https://blog.jetbrains.com/pycharm/2015/11/python-3-5-type-hinting-in-pycharm-5/
    (String-Based Hints)

    Edit: PEP 563: https://www.python.org/dev/peps/pep-0563/ improves upon this.