[Python] Is it possible to type annotate Python function parameter used as TypedDict key to...

Discussão em 'Python' iniciado por Stack, Dezembro 22, 2024.

  1. Stack

    Stack Membro Participativo

    While working through code challenges I am trying to use type annotations for all function parameters/return types. I use mypy in strict mode with the goal of no errors.

    I've spent some time on this one and can't figure it out - example of problem:

    from typing import Literal, NotRequired, TypedDict

    class Movie(TypedDict):
    Title: str
    Runtime: str
    Awards: str

    class MovieData(TypedDict):
    Awards: NotRequired[str]
    Runtime: NotRequired[str]

    def get_movie_field(movies: list[Movie], field: Literal['Awards', 'Runtime']) -> dict[str, MovieData]:
    return {movie['Title']: {field: movie[field]} for movie in movies}


    # Check with mypy 1.14.0:
    PS> mypy --strict .\program.py
    program.py:13: error: Expected TypedDict key to be string literal [misc]
    Found 1 error in 1 file (checked 1 source file)


    Is there some way to make this work? I realize I can append # type: ignore to the line but I'm curious if there's another way.

    I've tried a bunch of different permutations such as ensuring field matches one of the literal values before the dict comprehension but nothing seems to help.

    Continue reading...

Compartilhe esta Página