16

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?

2 Answers 2

21

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

Sign up to request clarification or add additional context in comments.

Comments

13

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.