[Python] Python typing. TypedDict. How to turn a non-required key into a required one?

Discussão em 'Python' iniciado por Stack, Fevereiro 12, 2025.

  1. Stack

    Stack Membro Participativo

    The code below defines a TypedDict with optional keys. The if statement in the middle raises an exception if a certain key is absent, which means that the next lines will be executed only if that key is present. It seems Pylance can't figure out this logic automatically. How am I supposed to handle this? Reassign a new typing to the same Dict somehow?

    output_dict_type = TypedDict(
    'some description',
    {
    'id': str
    'name': str
    },
    total=False
    )
    my_dict:eek:utput_dict_type = {
    'id': 'foo'
    }
    if not my_dict.get('name'):
    raise Exception('name is required')

    if my_dict['name'] == 'John': # type error: "name" is not a required key...
    do_stuff()

    Continue reading...

Compartilhe esta Página