Exclude type in Python typing annotation

旧时模样 提交于 2020-01-30 05:44:18

问题


I wrote the following function:

def _clean_dict(d):
    return {k: v for k, v in d.items() if v is not None}

I want to add type annotations to the function:

def _clean_dict(d: Dict[Any, Any]) -> Dict[Any, Any]:                           
    return {k: v for k, v in d.items() if v is not None}

However, I want to explicitly define that the values inside the returned dictionary cannot be None.

Is there a way to say "Any type, except NoneType" or "Every possible value but None"?


回答1:


Python type hinting can't exclude types. You can't exclude Nones, strs or any another type.

The only thing you can use to try to emulate None exclusion is to use Union and write every type you are actually using in the dictionary.



来源:https://stackoverflow.com/questions/57854871/exclude-type-in-python-typing-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!