Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

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

Open
BaxHugh opened this issue Dec 21, 2024 · 2 comments

Comments

@BaxHugh
Copy link

BaxHugh commented Dec 21, 2024

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"])
@BaxHugh
Copy link
Author

BaxHugh commented Dec 21, 2024

I think actually, in the bigger picture, there is lack of support / limitation for generic fields anyway.

It seems that deserializing with Foo[CustomInt], or just Foo as the target type, just returns the field as a dict, rather than trying to serialize to the specified generic.

@BaxHugh
Copy link
Author

BaxHugh commented Dec 22, 2024

Actually, not point addressing this issue without #624 being addressed first

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant