You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Enhanced Literal Detection: Allow string type narrowing to literals #16813
It would be great if mypy could detect and type narrow strings to Literals if this is statically detectable.
I.e. if accessing TypedDict or Enum values
Pitch
fromtypingimportTypedDictclassPart(TypedDict, total=False):
a: intb: intclassFull(Part, total=False):
c: intdefmake_part(full: Full) ->Part:
part: Part= {}
fork, vinfull.items():
ifkinPart.__annotations__:
part[k]=v# error: TypedDict key must be a string literal; expected one of ("a", "b") [literal-required]returnpart
Currently there is no way to type this kind of expression without a # type: ignore.
It would be nice if mypy could detect that if k in Part.__annotations__ will narrow k to the Literal of all key of Part.
Also if k == "a" isn't working at the moment, but at least for this I am able to write a TypeGuard.
Also if Literals are explicitly defined, we loose this once we are with a loop
Even if the literal is defined explictly, it gets lost in a for loop
This is a lot of different feature requests in one. You should probably open multiple issues. The one about __annotations__ might be a step too far, the others are more likely to be OK.
Activity
CarliJoy commentedon Jan 25, 2024
related to #13767
JelleZijlstra commentedon Jan 25, 2024
This is a lot of different feature requests in one. You should probably open multiple issues. The one about
__annotations__might be a step too far, the others are more likely to be OK.CarliJoy commentedon Jan 25, 2024
I will create different issues an link them here. After this I will close this issue.
CarliJoy commentedon Jan 25, 2024
Opened three different Issues that should tackle this.
CarliJoy commentedon Jan 26, 2024
Note this already works in pyright
Correction: Pyright just doesn't check this correctly
bcmills commentedon Feb 6, 2025
Literalusinginsyntax #12535 is another specific case pertaining to this request.