Replies: 2 comments 1 reply
-
This is kind of similar to the example here, although without respect to overloads: https://github.com/microsoft/pyright/blob/main/docs/mypy-comparison.md#constraint-solver-ambiguous-solution-scoring Curious, what do you get from Pyright? |
Beta Was this translation helpful? Give feedback.
-
Your first attempt "works", if I change from typing import TypeVar, overload, Any, Union
T = TypeVar("T")
@overload
def ensure_tuple_or_list(obj: list[T]) -> list[T]: # type: ignore
...
@overload
def ensure_tuple_or_list(obj: tuple[T, ...]) -> tuple[T, ...]: # type: ignore
...
@overload
def ensure_tuple_or_list(obj: T) -> tuple[T]:
...
def ensure_tuple_or_list(obj: list[T] | tuple[T, ...] | T) -> list[T] | tuple[T, ...]:
if isinstance(obj, (list, tuple)):
return obj # type: ignore
return (obj,)
reveal_type(ensure_tuple_or_list(1)) # Tuple[int]
reveal_type(ensure_tuple_or_list((1,))) # Tuple[int]
reveal_type(ensure_tuple_or_list([1])) # list[int] You need to use Consider this, for example: x: int | list[int]
reveal_type(ensure_tuple_or_list(x)) # Tuple[Union[builtins.int, builtins.list[builtins.int]]] Because the type |
Beta Was this translation helpful? Give feedback.
-
Consider the following function:
How exactly do I annotate this better than the information-lossy
(obj: Any) -> list | tuple
?My first attempt:
Mypy 1.1.1 with default settings rejects this with:
For my second attempt, I tried having the function always return a tuple:
Mypy rejects this with:
For my third attempt, I switched to using
functools.singledispatch
:Mypy rejects this with:
Variations on this last one (which I will omit for brevity) similarly proved fruitless.
Help?
Beta Was this translation helpful? Give feedback.
All reactions