Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type annotating a class that is defined later (Forward Reference)

For style reasons I'm trying to keep definition of myDict before class Foo. This will cause a NameError because Foo is not yet defined.

from typing import Dict

myDict: Dict[str, Foo] = {}

class Foo:
    pass

Moving myDict below Foo obviously fixes this, but is there any way I can keep myDict and its annotation up top?

like image 571
rawr rang Avatar asked Dec 28 '25 20:12

rawr rang


2 Answers

Depending on which version on python (Py3.7+) you are running you can:

from __future__ import annotations

Then your code runs as is. PEP 563 introduced a delayed evaluation of annotations which means you don't need to use the original approach of putting the type in quotes, e.g. 'Foo'.

like image 106
AChampion Avatar answered Dec 30 '25 10:12

AChampion


You can quote it as follows:

from typing import Dict

myDict: Dict[str, 'Foo'] = {}

class Foo:
    pass

See https://www.python.org/dev/peps/pep-0484/#forward-references for more information.

like image 45
Kent Shikama Avatar answered Dec 30 '25 10:12

Kent Shikama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!