3

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Ryan Schaefer
  • 3,047
  • 1
  • 26
  • 46
  • Also related: [How do I specify that the return type of a method is the same as the class itself?](https://stackoverflow.com/questions/33533148/how-do-i-specify-that-the-return-type-of-a-method-is-the-same-as-the-class-itsel) – Georgy Jul 30 '19 at 18:34

1 Answers1

4

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.

ruohola
  • 21,987
  • 6
  • 62
  • 97
  • Why does the class need it in quotes for when it is in itself but not when it is in another class? I find this behavior somewhat odd – Ryan Schaefer Jul 30 '19 at 15:33
  • @RyanSchaefer Because the type-annotations in the class cannot "see" the class when annotating in the class. The class type is not yet defined. – ruohola Jul 30 '19 at 15:35
  • Could you attach a link to some documentation about this? – Tomerikoo Jul 30 '19 at 15:36
  • Ahh, that somewhat makes sense. Does the type hint function in a similar manner to the one in the consumable class? – Ryan Schaefer Jul 30 '19 at 15:36
  • 1
    @Tomerikoo Added a source – ruohola Jul 30 '19 at 15:36
  • @RyanSchaefer Yes it does, this doesn't infer with the type annotations at all, and it's simply a cosmetic thing that it looks different. – ruohola Jul 30 '19 at 15:37
  • That link is extremely helpful, thank you. I guess I just didn't know the terminology for what I was trying to do, it makes sense now that I now this is a forward reference – Ryan Schaefer Jul 30 '19 at 15:38
  • @RyanSchaefer Glad I could help! Added also a link to Pycharm blog. – ruohola Jul 30 '19 at 15:47