2

I have code similar to this example

import typing

class C():
    def __init__(self, callback: typing.Callable[[C], int]):
        self._callback = callback

    def getCallback() -> typing.Callable[[C], int]:
        return self._callback

class C2():
    def __init__(self, cInstance: C):
        self._cInstance = cInstance

    def f() -> typing.NoReturn:
        self._cInstance.getCallback()(self.cInstance)

and I want to add a type alias for typing.Callable[[C], int]

However when I try to do this

import typing

CallbackType = typing.Callable[[C], int] # ERROR: C not defined

class C():
    def __init__(self, callback: CallbackType):
        self._callback = callback

    def getCallback() -> CallbackType:
        return self._callback

class C2():
    def __init__(self, cInstance: C):
        self._cInstance = cInstance

    def f() -> typing.NoReturn:
        self._cInstance.getCallback()(self.cInstance)

I get the error that C was not defined at the time. If I define the CallbackType after class C, then CallbackType is not defined in C's __init__. In the example the typing is short enough, but in my actual code it's quite complex, which is why I want to add the alias.

FalcoGer
  • 2,278
  • 1
  • 12
  • 34

1 Answers1

2

You can use forward references:

CallbackType = typing.Callable[['C'], int]
InSync
  • 4,851
  • 4
  • 8
  • 30