[Python] Type hint warning `"keys" is not a known attribute of "None"` for `Optional` in...

Discussão em 'Python' iniciado por Stack, Junho 4, 2025.

  1. Stack

    Stack Membro Participativo

    Recently Pylance has started to add red underlines in my code. I've managed to fix most of it, but I have problems with Optional typing:

    def realms(testenv:str, active:bool=True) -> Optional[Dict]:
    """ return a dict of active/inactive realms with info from keycloak, on error return None """
    dat = api(testenv, endpoint="/admin/realms")
    :

    all_realms = list(realms(testenv, active=False).keys())
    ------


    Pylance says:


    "keys" is not a known attribute of "None"
    ​

    If I change the def prototype to:

    def realms(testenv:str, active:bool=True) -> Dict:


    I get small issues with return None I can fix with raise exceptions, or just remove it.

    The code workaround can be a two-liner:

    all_realms_dict = realms(testenv, active=False)
    all_realms = list(all_realms_dict.keys()) if all_realms_dict else []


    Should I stop using Optional and switch to raising exceptions? Is returning None a bad idea?

    Continue reading...

Compartilhe esta Página