6

New way of type/hinting/assignments is cool, but I don't know how to make such a simple thing work:

class MyContainer:
    def addMyItem(self, item:MyItem):
        pass

class MyItem:
    def __init__(self, container:MyContainer):
        pass

It throw an error: Using variable 'MyItem' before assignment. The best but super ugly workaround I found so far is this:

class MyContainer:
    def addMyItem(self, untypeditem):
        item:MyItem=untypeditem
        pass

class MyItem:
    def __init__(self, container:MyContainer):
        pass

Please tell me that language with #1 principle Beautiful is better than ugly has something better to solve this common typing issue

Philipp Munin
  • 5,610
  • 7
  • 37
  • 60

1 Answers1

11

Forward references are just strings referring to the name (as it is visible in the module).

class MyContainer:
    def addMyItem(self, item: 'MyItem'):
        pass

class MyItem:
    def __init__(self, container: 'MyContainer'):
        pass

If you need to import the name from somewhere else (and you only need the name for type checking, or if it might cause a circular import), you can use

import typing

if typing.TYPE_CHECKING:
    from foo import Thing

TYPE_CHECKING is true only when a type checker is running (i.e. your code is not being evaluated for execution).

AKX
  • 152,115
  • 15
  • 115
  • 172