Skip to content

Type narrowing based on variable #1282

Answered by erictraut
Andarius asked this question in Q&A
Discussion options

You must be logged in to vote

The type Literal[True, False] is the same as bool.

In your example, you need to provide a fallback overload with bool parameter types. There will be times (like in your final code snippet) where a type checker cannot determine statically whether an argument type is Literal[True] or Literal[False] and can only determine that it's bool. You need an overload that handles this case.

@overload
def get_class(with_conflict: bool, with_returning: bool) -> WithReturningConflict | WithConflict | WithReturning | QueryBase: ...

If you are designing an new API and want it to work well with static type checking, you might want to avoid creating such a polymorphic method — one that returns many varying …

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by Andarius
Comment options

You must be logged in to vote
0 replies
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