Replies: 2 comments 2 replies
-
Typechecks cannot be sure if In case of So, why won't you just stick to the first or the second form? 🙂 |
Beta Was this translation helpful? Give feedback.
-
Was able to achieve the effect I was going for using a custom mypy plugin with the following type analyze hook: def commute_with_union_hook(ctx: AnalyzeTypeContext) -> Type:
if ctx.type.args and len(ctx.type.args) == 1:
t: Type = ctx.type.args[0]
t = ctx.api.anal_type(t)
sym = ctx.api.lookup_qualified(ctx.type.name, ctx.type)
node = sym.node
if not isinstance(t, UnionType):
wrapper = ctx.api.analyze_type_with_type_info(node, ctx.type.args, ctx.type)
return wrapper
else:
union_wrapper = UnionType.make_union(
items=[Instance(typ=node, args=[item]) for item in t.items]
)
return union_wrapper
return ctx.type This feels quite crude, but it works for the examples I had in mind. Heavily inspired by the |
Beta Was this translation helpful? Give feedback.
-
I have already posted a lengthy version of this question on stackoverflow, but I discovered this forum and thought it would be a just as good place to ask. Extended version: https://stackoverflow.com/questions/69209879/generic-type-interplay-with-union-type
TLDR:
Does there exist a way to specify that a type commutes with
Union
? In other words, how do I get this example past a type checker?Beta Was this translation helpful? Give feedback.
All reactions