Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to alias a type used in a class before it is declared?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

You can use forward references:

CallbackType = typing.Callable[['C'], int]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading