Skip to content

Generic with bound defined as a string type annotation of a union "type_1 | type_2" does not work #623

@BaxHugh

Description

@BaxHugh

Not a particularly pressing bug, and perhaps a bug in beartype rather than pyserde.
Workarounds are documented below.

To reproduce:

from typing import Generic, TypeVar

import serde

# Assuming CustomInt must be declared after T
# we need to use a string for the union type bound
T = TypeVar("T", bound="int | CustomInt")


class CustomInt(int):
    pass


# This fails with
# `beartype.roar.BeartypeDecorHintForwardRefException: Forward reference 'int | CustomInt' not valid Python attribute name.`
@serde.serde
class Foo(Generic[T]):
    bar: T

Workarounds:

  • Define CustomInt class before the type var, so that a string type annotation is not needed. However, this may not always be possible perhaps?
  • Use the typing.Union instead of Union syntax:
T = TypeVar("T", bound=Union[int, "CustomInt"])

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions