bux
bux

Reputation: 7739

How declare type of dict containing classes

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 ?

Upvotes: 2

Views: 301

Answers (1)

falsetru
falsetru

Reputation: 368894

The code is using the class C itself as a key, not an instance of the C.

my_func({C: 'foo'})

Passing the instance of C class should be fine.

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

If you really need to pass the class itself (I doubt it), you need to use typing.Type:

typing.Dict[typing.Type[A], str]
            ^^^^^^^^^^^^^^

Upvotes: 3

Related Questions