Reputation: 973
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
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
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