pythonurllibpython-typingmypy

error: Value of type variable "AnyStr" of "urljoin" cannot be "Optional[str]" in mypy


I have a statement like this:

import os
from urllib.parse import urljoin

ES_SEARCH_URL = urljoin(base=os.getenv("ELASTICSEARCH_URL"), url="index/_search")

I have tried with giving many types for ES_SEARCH_URL, but it always gives the following error whenever I run mypy.

error: Value of type variable "AnyStr" of "urljoin" cannot be "Optional[str]"

Options I have tried so far:

from typing import Optional, AnyStr, Union
ES_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")

How to resolve this error? Please help.
Python version: Python 3.8


Solution

  • Since os.getenv can return None mypy can't know if it's a string value or a None.

    Try giving it a default:

    os.getenv("ELASTICSEARCH_URL", default="http://some.url.example.com/")
    

    or handle the None case:

    base_url = os.getenv("ELASTICSEARCH_URL")
    if base_url is None:
      # handle here
    ES_SEARCH_URL = urljoin(base=base_url, url="index/_search")
    

    Reference: this github issue