4 ms·
I maintain a library for doing exactly this in C# (https://github.com/mcintyre321/OneOf https://github.com/mcintyre321/OneOf). I tried to replicate it in Python
by macca321 7y ago
I maintain a library for doing exactly this in C# (https://github.com/mcintyre321/OneOf https://github.com/mcintyre321/OneOf). I tried to replicate it in Python as I'm writing it at the moment, but couldn't quite manage it. Can you have a multi generic typed Union in python?
- Recursing 7y agoDo you mean something like this? T1 = TypeVar("T1") T2 = TypeVar("T2") GenericUnion = Union[T1, T2]
- macca321 7y agoYes I can't quite remember why I couldn't get it to work. I want to make something where this is valid, but couldn't manage it: def foo() -> OneOf[Bar, Baz]: if blah(): return Bar() return Baz() def bar_to_blah(bar:Bar) -> Blah : ... def baz_to_blah(baz:Baz) -> Blah : ... one_of_bar_or_baz = foo() blah = one_of_bar_or_baz.match(bar_to_blah, baz_to_blah) but the critical thing is to get a type error if you add another case to foo's return type, or change the generics to different types.