Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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.

>Solution :

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'>)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading