0

For instance, I want

from typing import Dict, List
check_derived(Dict[int, int], Dict) == True
check_derived(List[str], List) == True
check_derived(List, Dict) == False

and so on.

Do I have to write my own mapping of derived classes to classes in order to achieve this? Seems hacky.

Cory Nezin
  • 1,551
  • 10
  • 22
  • 1
    Possible duplicate of [List all base classes in a hierarchy of given class?](https://stackoverflow.com/questions/1401661/list-all-base-classes-in-a-hierarchy-of-given-class) – Green Cloak Guy Oct 28 '19 at 20:56
  • Like this, I will say that is not usefull as Dict[x, x] is a Dict what ever are inside. Are you looking for `isinstance`? – Florian Bernard Oct 28 '19 at 20:57

1 Answers1

0

Thanks @Green Clock Guy, that seems to have worked!

import inspect
from typing import Dict, List

def check_derived(left, right):
  """True if left derived from right"""
  left_classes = inspect.getmro(left)
  return right in left_classes

assert check_derived(Dict[int, int], Dict) == True
assert check_derived(List[str], List) == True
assert check_derived(List, Dict) == False

Edit: However I see that this fails for the case

assert check_derived(Union[str, int], int) == True
Cory Nezin
  • 1,551
  • 10
  • 22