Skip to content

Wrong mypy annotation for _TYPE_HOSTS #2321

Closed
@pklejch

Description

@pklejch

Elasticsearch version (bin/elasticsearch --version): 8.9.0 (but it's not relevant to this bug)

elasticsearch-py version (elasticsearch.__versionstr__): 8.10.0

Description of the problem including expected versus actual behavior:
Currently _TYPE_HOSTS has type annotation defined as

_TYPE_HOSTS = Union[str, List[Union[str, Mapping[str, Union[str, int]], NodeConfig]]]

The problem is that List is invariant and thus List[str] is not valid subtype for List[Union[str, Mapping[str, Union[str, int]], NodeConfig]]]

See common mypy issue python/mypy#3351

The solution is to replace List with Sequence.

Steps to reproduce:
Minimal example

import elasticsearch

HOSTS = ['http://localhost:9200', 'http://localhost:10200']  # this will be inferred as list[str]

client = elasticsearch.Elasticsearch(hosts=HOSTS)

Mypy output

test.py:5: error: Argument "hosts" to "Elasticsearch" has incompatible type "list[str]"; expected "str | list[str | Mapping[str, str | int] | NodeConfig] | None"  [arg-type]
test.py:5: note: "List" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
test.py:5: note: Consider using "Sequence" instead, which is covariant

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions