rawr rang
rawr rang

Reputation: 973

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?

Upvotes: 13

Views: 4033

Answers (2)

AChampion
AChampion

Reputation: 30268

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'.

Upvotes: 18

Kent Shikama
Kent Shikama

Reputation: 4060

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.

Upvotes: 12

Related Questions