George Isaacs
George Isaacs

Reputation: 33

Python find type of value for typing.Dict

If I have

class A:
    pass

def my_func(my_dict: typing.Dict[str, A]):
    pass

How can I find the type of the values in this dict? Basically, how can I figure out that the values that go into my_dict are supposed to be of type A?

To give some context I have two dataclasses

@dataclass
class B:
    x: str

@dataclass
class C:
    y: Dict[str, B]

I'm trying to look at class C and figure out which object I need to instantiate. In this example, I want to create object B.

class_type = C.__annotations__["y"]  # this returns typing.Dict[str, B]
# now need to create the object
b = class_type[1](x="bar")  # index 1 to retrieve the B class in typing.Dict[str, B]
c = C(y = {"foo": b})

I'm trying to create b but obviously index of 1 in a mutable map doesn't work.

Upvotes: 3

Views: 425

Answers (1)

sudden_appearance
sudden_appearance

Reputation: 2197

Combine answer from here with __annotations__[<key>] and you will get what you need

print(typing.get_args(my_func.__annotations__['my_dict']))
# will return (<class 'str'>, <class '__main__.A'>)

Upvotes: 3

Related Questions