-
Notifications
You must be signed in to change notification settings - Fork 41
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Union of generics doesn't work #301
Comments
Hi @Kobzol! Thank you for reporting a bug, and making awesome OSS! (I am a cargo-pgo user) Unfortunately, union generics is not yet supported as of now. In your example code, if you pass wrapper = Wrapper(inner=ClassB(a=1), meta="foo")
print(from_dict(InnerType, to_dict(wrapper)))
# Wrapper(inner=ClassA(a=1), meta='foo') - wrong |
Thanks! I was mostly just fooling around with some data model idea that I had and I noticed that there is a weird behavior mismatch with generics + unions when the field is nested. I didn't realize that even the non-nested use case isn't currently supposed to work :) |
Do you know how to correctly type check Generic instances? Maybe I need to implement my own? 🤔 This raises isinstance(GenericFoo[str](10), GenericFoo[int])
isinstance(GenericFoo[int](10), GenericFoo[str]) This always evaluates to true isinstance(GenericFoo[str](10), GenericFoo[int])
isinstance(GenericFoo[int](10), GenericFoo[str]) |
Maybe with this? >>> typing.get_args(Foo[int])
(<class 'int'>,) |
@Kobzol Thanks, I find from typing import Generic, TypeVar, Any, get_origin, get_args
from dataclasses import dataclass
T = TypeVar("T")
@dataclass
class Foo(Generic[T]):
v: T
def is_generic_instance(o: Any, cls: Any) -> bool:
return isinstance(o, get_origin(cls)) and get_args(o.__orig_class__) == get_args(cls)
assert not is_generic_instance(Foo[int](1), Foo[str])
assert is_generic_instance(Foo[int](1), Foo[int]) |
That's.. unfortunate, indeed. But I'm not sure that we can do better, since Python doesn't really have any type inference for this. We could maybe do something like this:
But it's incredibly hacky, probably quite difficult and won't work in all cases :) |
Yeah, that's also what I thought. |
Hi! Thanks for this wonderful library (
serde
FTW!). I was experimenting with it and noticed a strange behavior that happens when generics and union is combined within a dataclass nested field. Here's a minimal reproduction:Basically, when I have a union of generics, and serialize + deserialize it, it deserializes correctly. However, when the same thing is deserialized as a field of another serde dataclass, it doesn't serialize the nested field correctly.
The text was updated successfully, but these errors were encountered: