Skip to content

Wrong type annotations for read only mapping types. #2244

@RasmusNygren

Description

@RasmusNygren

There are type annotations that uses Dict to annotate read-only mapping arguments, e.g. the conf argument here:

def __init__(self, conf: Dict[str, Union[str, int, float, bool]], **kwargs: Any) -> None:

The problem is that Dict is invariant in its value type, meaning that in the example above where conf is typed as conf: Dict[str, Union[str, int, float, bool] it is not valid to assign a dict of type Dict[str, str].

That means code like this

from confluent_kafka.admin import AdminClient
conf = {
    "bootstrap.servers": "kafka:9092"),
} # inferred type dict[str, str]
admin_client = AdminClient(conf)

is rejected by type-checkers.

The solution here would be to annotate conf with collections.abc.Mapping instead of Dict, as Mapping is covariant in its value-type.

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