2

I'm tring to declare type of following function parameter with typing module:

import typing


class A(object):
    pass

class B(A):
    pass

class C(B):
    pass

def my_func(p: typing.Dict[A, str]) -> None:
    pass

my_func({C: 'foo'})

p parameter of my_func must be dict with childclass of A as key and str as value. Actual notation fail with mypy check:

example.py:17: error: List item 0 has incompatible type "Tuple[C, str]"

How to declare type of p with typing ?

4

1 回答 1

3

代码使用类C本身作为键,而不是C.

my_func({C: 'foo'})

传递 C 类的实例应该没问题。

my_func({C(): 'foo'})
         ^^^--- instance, not a class itself

如果您真的需要通过课程本身(我对此表示怀疑),您需要使用typing.Type

typing.Dict[typing.Type[A], str]
            ^^^^^^^^^^^^^^
于 2017-01-24T08:11:59.323 回答