我有一个非常简单的函数:
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
,但这没有区别。此函数工作正常。
这是预期的行为吗?如何修复错误。
谢谢!
在_check_in = check_in.strftime("%Y-%m-%d")
的第一行中,_check_in
是一个字符串(或 mypy 喜欢认为的str
(,然后在_check_in = _check_in.split("-")
_check_in
中成为字符串列表 (List[str]
(,因为 mypy 已经认为这应该是一个str
,它会抱怨(或者更确切地说是警告你,因为这不是一个特别好的做法(。
至于你应该如何修复它,只需适当地重命名变量,或者如果你死心塌地地使用_check_in
作为变量名称,你可以做_check_in = _check_in.split("-") # type: List[str]
(也_check_in = _check_in[1] + "%2F" + _check_in[2] + "%2F" + _check_in[0] # type: str
下面的行(。
编辑
也许你想这样做
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'),
)
似乎对我有用吗?这是我对你的代码的实现
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