I have this very simple function:
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 throws the following error:
error:Incompatible types in assignment (expression has type "List[str]", variable has type "str")
for line 6 _check_in = _check_in.split("-")
.
I've tried renaming _check_in
on line 6 but that makes no difference. This function works fine.
Is this the expected behavior? How do I fix the error.
Thanks!
In the first line _check_in = check_in.strftime("%Y-%m-%d")
, _check_in
is a string (or str
as mypy like to think), then in _check_in = _check_in.split("-")
_check_in
becomes a list of string (List[str]
), since mypy already think this should be a str
, it will complain (or rather warn you about it as it's not a particularly nice practice).
As for how you should fix it, just rename the variable appropriately, or you can do _check_in = _check_in.split("-") # type: List[str]
(and also _check_in = _check_in[1] + "%2F" + _check_in[2] + "%2F" + _check_in[0] # type: str
the line below) if you are dead set on using _check_in
as the variable name.
Maybe you want to do this instead
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'),
)