Skip to content
Advertisement

How do I use type hint for multiple classes in a dictionary but they inherit from same parent class?

I want to use type hint with string as a key and different classes as a value in a dictionary like below.

JavaScript

The classes Dev, Product, Test inherit from a base class “Parent”.

JavaScript

What is the best way to do the type hint for this?

Do I need to set just “Any” as their type?

Advertisement

Answer

Depends on how accurate you want your hints to be,

  1. Use the parent class
JavaScript
  1. Specify the classes in a union
JavaScript
  1. Create a TypedDict type for this specific dict
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement