【问题标题】:mypy error:Incompatible types in assignment (expression has type "List[str]", variable has type "str")mypy 错误:赋值中的类型不兼容(表达式的类型为“List[str]”,变量的类型为“str”)
【发布时间】:2018-05-28 09:11:26
【问题描述】:

我有这个非常简单的功能:

import datetime

def create_url(check_in: datetime.date) -> str:
"""take date such as '2018-06-05' and transform to format '06%2F05%2F2018'"""
    _check_in = check_in.strftime("%Y-%m-%d")
    _check_in = _check_in.split("-")
    _check_in = _check_in[1] + "%2F" + _check_in[2] + "%2F" + _check_in[0]

    return f"https://www.website.com/?arrival={_check_in}"

mypy 抛出以下错误: error:Incompatible types in assignment (expression has type "List[str]", variable has type "str") 第 6 行 _check_in = _check_in.split("-")。 我尝试在第 6 行重命名 _check_in,但这并没有什么区别。此功能工作正常。

这是预期的行为吗?如何修复错误。

谢谢!

【问题讨论】:

  • 顺便说一句,您的代码缺少一个额外的",这会导致您的代码块像文档字符串一样格式化
  • 谢谢 - 现在已更正。

标签: python python-3.x mypy


【解决方案1】:

在第一行_check_in = check_in.strftime("%Y-%m-%d")_check_in 是一个字符串(或者str 就像mypy 想的那样),然后在_check_in = _check_in.split("-") _check_in 变成一个字符串列表(List[str]),因为mypy已经认为这应该是str,它会抱怨(或者更确切地说警告你,因为这不是一个特别好的做法)。

至于你应该如何修复它,只需适当地重命名变量,或者你可以使用_check_in = _check_in.split("-") # type: List[str](也可以在下面的行中使用_check_in = _check_in[1] + "%2F" + _check_in[2] + "%2F" + _check_in[0] # type: str),如果你死心塌地使用_check_in作为变量名。

编辑

也许你想这样做

import datetime

def create_url(check_in: datetime.datetime) -> str:
    return "https://www.website.com/?arrival={0}".format(
        check_in.strftime('%d%%2F%m%%2F%Y'),
    )

【讨论】:

  • 这实际上使 mypy 进入“错误:名称 '_check_in' 已定义”。如果我在每一行上为 check_in 使用不同的名称,mypy 将保持沉默。在这样一个简单的函数中为 check_in 使用四个名称似乎很不合 Python。
  • 编辑了我的答案以获得建议:)
【解决方案2】:

对我来说似乎工作正常?这是我对你的代码的实现

import datetime

def create_url(check_in):
    """take date such as '2018-06-05' and transform to format '06%2F05%2F2018'"""
    _check_in = check_in.strftime("%Y-%m-%d")
    _check_in = _check_in.split("-")
    _check_in = _check_in[1] + "%2F" + _check_in[2] + "%2F" + _check_in[0]

    return "https://www.website.com/?arrival={0}".format(_check_in)

today = datetime.date.today()
print(create_url(today))

>>> https://www.website.com/?arrival=05%2F28%2F2018

【讨论】:

  • 它工作正常,如问题中所述。问题是为什么 mypy 会抛出错误。
  • 您的示例代码不会导致 mypy 出错的原因是没有输入 check_in 参数。 Mypy 将Any 的类型分配给check_in,这导致_check_in 也被分配了Any 的类型。
猜你喜欢
  • 2021-10-18
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
相关资源
最近更新 更多