我有这样的声明:import osfrom urllib.parse import urljoinES_SEARCH_URL = urljoin(base=os.getenv("ELASTICSEARCH_URL"), url="index/_search")我尝试为 提供多种类型ES_SEARCH_URL,但每当我运行 mypy.error: Value of type variable "AnyStr" of "urljoin" cannot be "Optional[str]"到目前为止我尝试过的选项:from typing import Optional, AnyStr, UnionES_SEARCH_URL: Union[str, None] = urljoin(base=os.getenv("ELASTICSEARCH_URL"), url="index/_search")ES_SEARCH_URL: Optional[str] = urljoin(base=os.getenv("ELASTICSEARCH_URL"), url="index/_search")ES_SEARCH_URL: Optional[AnyStr] = urljoin(base=os.getenv("ELASTICSEARCH_URL"), url="index/_search")如何解决此错误?请帮忙。Python版本:Python 3.8
1 回答
MMMHUHU
TA贡献1834条经验 获得超8个赞
由于os.getenvcan return Nonemypy 无法知道它是字符串值还是None.
尝试给它一个默认值:
os.getenv("ELASTICSEARCH_URL", default="http://some.url.example.com/")
或处理None此案:
base_url = os.getenv("ELASTICSEARCH_URL")
if base_url is None:
# handle here
ES_SEARCH_URL = urljoin(base=base_url, url="index/_search")
添加回答
举报
0/150
提交
取消