【问题标题】:Argument of type "Literal[False, xxx]" cannot be assigned to parameter "__o" of type "Iterable" in function "__setitem__"类型为 \"Literal[False, xxx]\" 的参数不能分配给函数 \"__setitem__\" 中类型为 \"Iterable\" 的参数 \"__o\"
【发布时间】:2022-12-09 04:19:35
【问题描述】:

我的代码可以简化为:

from typing import Union, Any, Dict, List, Tuple

def myFunc() -> Union[object, Dict, List, str,
                      int, float, bool, None]:
  something = { 'prop': 123}
  return something

obj = myFunc()
obj['k'] = isinstance(obj, Dict) and 321

我从 Pylance 得到了这样的例外:

(variable) obj: object | List | str | int | float | bool | Dict | None
"__setitem__" method not defined on type "object"PylancereportGeneralTypeIssues
"__setitem__" method not defined on type "str"PylancereportGeneralTypeIssues
"__setitem__" method not defined on type "int"PylancereportGeneralTypeIssues
"__setitem__" method not defined on type "float"PylancereportGeneralTypeIssues
"__setitem__" method not defined on type "bool"PylancereportGeneralTypeIssues
Argument of type "Literal['k']" cannot be assigned to parameter "__s" of type "slice" in function "__setitem__"
  "Literal['k']" is incompatible with "slice"PylancereportGeneralTypeIssues

可能是什么问题?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    问题在于假设 obj['k'] 始终有效,但 List | str | int | float | bool | None 并非如此。解决办法是将最后一行改写如下:

    obj = isinstance(obj, Dict) and {**obj, 'k': 123}
    

    完整的例子如下:

    from typing import Union, Any, Dict, List, Tuple
    
    def myFunc() -> Union[object, Dict, List, str,
                          int, float, bool, None]:
      something = { 'prop': 123}
      return something
    
    obj = myFunc()
    obj = isinstance(obj, Dict) and {**obj, 'k': 123}
    

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 2021-11-23
      • 2021-11-13
      • 2021-12-24
      • 2021-07-25
      • 2021-05-25
      • 2021-01-29
      • 2021-06-26
      • 2021-07-10
      相关资源
      最近更新 更多