Input: incompatible type when typing.Type [] is declared

For the following code

# -*- coding: utf-8 -*-
import typing


class A(object):
    pass

class B(A):
    pass

class C(A):
    pass

class D(A):
    pass

class E(A):
    pass

MAPPING_X = {
    B: 'b',
    C: 'c',
}
MAPPING_Y = {
    D: 'd',
    E: 'e',
}

all_mappings = {}  # type: typing.Dict[typing.Type[A], str]
all_mappings.update(MAPPING_X)
all_mappings.update(MAPPING_Y)

mypy returns the following errors (python 3.4):

t.py:30: error: Argument 1 to "update" of "dict" has incompatible type Dict[type, str]; expected Mapping[Type[A], str]
t.py:31: error: Argument 1 to "update" of "dict" has incompatible type Dict[type, str]; expected Mapping[Type[A], str]

I do not understand how to indicate that I want subclasses Aas Dict keys. How to declare a type?

+4
source share
2 answers

Perhaps I don’t understand how the modules work typingand mypy, but there seems to be some kind of error happening here. If I do this (the example is adapted from the typing.Type docs section ):

import typing

class User(): pass
class BasicUser(User): pass

def make_new(u: typing.Type[User]) -> User:
    return u()

x = make_new(BasicUser)

There is mypyno error . If I do this:

import typing

class A():
    pass

MAPPING_X = {
    A: 'a',
}
all_mappings = {}  # type: typing.Dict[typing.Type[A], str]
all_mappings.update(MAPPING_X)

The error is also missing. However, this causes an error mypy:

import typing

class A():
    pass

class B(A):
    pass

MAPPING_X = {
    A: 'a',
    B: 'b',
}

all_mappings = {}  # type: typing.Dict[typing.Type[A], str]
all_mappings.update(MAPPING_X)

Based on my understanding of the documentation, this error should not occur.

0

, , MAPPING_X MAPPING_Y. .

# -*- coding: utf-8 -*-
import typing

class A(object):
    pass

class B(A):
    pass

class C(A):
    pass

class D(A):
    pass

class E(A):
    pass

MAPPING_X = {}  # type: typing.Dict[typing.Type[A], str]
MAPPING_Y = {}  # type: typing.Dict[typing.Type[A], str]

MAPPING_X = {
    B: 'b',
    C: 'c',
}
MAPPING_Y = {
    D: 'd',
    E: 'e',
}

all_mappings = {}  # type: typing.Dict[typing.Type[A], str]
all_mappings.update(MAPPING_X)
all_mappings.update(MAPPING_Y)

mypy.

, , .

0

Source: https://habr.com/ru/post/1668750/


All Articles