我對 python 型別注釋有一些理解問題。考慮以下用于將 dict 轉換為標準化格式的函式
from __future__ import annotations # needed for type annotations in > python 3.7
from typing import Dict, List, Union
class Producer(object):
pass
def normalize_producers(
producers: Dict[str, Union[Producer, List[Producer]]]
) -> Dict[str, List[Producer]]:
"""
Function to normalize producer input to have the same format
"""
normalized_dict: Dict[str, List[Producer]] = {}
for key in producers.keys():
if isinstance(producers[key], list):
normalized_dict[key] = producers[key]
else:
normalized_dict[key] = [producers[key]]
return normalized_dict
此示例導致分配的型別問題normalized_dict:
Argument of type "Producer | List[Producer]" cannot be assigned to parameter "v" of type "List[Producer]" in function "__setitem__"
Type "Producer | List[Producer]" cannot be assigned to type "List[Producer]"
"Producer" is incompatible with "List[Producer]"
Argument of type "list[Producer | List[Producer]]" cannot be assigned to parameter "v" of type "List[Producer]" in function "__setitem__"
TypeVar "_T@list" is invariant
Type "Producer | List[Producer]" cannot be assigned to type "Producer"
"List[Producer]" is incompatible with "Producer"
但是,當我使用臨時串列并檢查此串列的型別時,不會引發任何型別問題:
def normalize_producers_save(
producers: Dict[str, Union[Producer, List[Producer]]]
) -> Dict[str, List[Producer]]:
"""
Function to normalize producer input to have the same format
"""
normalized_dict: Dict[str, List[Producer]] = {}
for key in producers.keys():
templist = producers[key]
if isinstance(templist, list):
normalized_dict[key] = templist
else:
normalized_dict[key] = [templist]
return normalized_dict
這是否意味著,盡管我將 的值分配producers為 typeProducer或List[Producer] if isinstance(producers[key], list):不會導致producers[key]始終為 list 型別?我不明白,該功能的第一個版本有什么問題。
uj5u.com熱心網友回復:
這是一個已知問題,mypy因為它不會縮小像dict_var[key]. 作為解決方法,您可以對字典值使用顯式變數:
from __future__ import annotations # needed for type annotations in > python 3.7
from typing import Dict, List, Union
class Producer(object):
pass
def normalize_producers(
producers: Dict[str, Union[Producer, List[Producer]]]
) -> Dict[str, List[Producer]]:
"""
Function to normalize producer input to have the same format
"""
normalized_dict: Dict[str, List[Producer]] = {}
for key, value in producers.items():
if isinstance(value, list):
normalized_dict[key] = value
else:
normalized_dict[key] = [value]
return normalized_dict
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/353557.html
下一篇:遍歷類物件
