Typing Syntax: Forward Reference Union Type

Build on PEP484 and PEP604 to permit the newer union type syntax annotations with Forward References. See the following syntax:


class Example:
    a: int | "Forward"
    b: float

def function(a: int | "Forward"): ...


class Forward:
    a: int

Currently, this syntax raises the following error:
TypeError: unsupported operand type(s) for |: 'type' and 'str'

The current workaround is to use the previous union type annotation:

from typing import Union

class Example:
    a: Union[int, "Forward"]

1 Like

More typically, you would enclose the entire annotation in quotes, which avoids this issue.

a: "int | Forward"

Alternatively, use from __future__ import annotations, which eliminates the need to use quotes altogether.

1 Like