Skip to content

How to type a function that always return a list? #995

Answered by cdce8p
cdce8p asked this question in Q&A
Discussion options

You must be logged in to vote

By coincidence I found an overload variation that works in both mypy and pyright.

@overload
def ensure_list(value: None) -> list[Any]: ...

@overload
def ensure_list(value: list[T]) -> list[T]: ...

@overload
def ensure_list(value: list[T] | T) -> list[T]: ...

def ensure_list(value: T | None) -> list[T] | list[Any]: ...

Extracting the concrete overload list[T] -> list[T] while also keeping the union one Eric suggested list[T] | T - > list[T] seems to work. Note the implementation type for value is only T | None. Unfortunately list[T] | T | None doesn't work in mypy although arguably a bit more fitting. T | None does work though in both mypy and pyright.

error: Overloaded function impleme…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
2 replies
@cdce8p
Comment options

@erictraut
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by cdce8p
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants