4

Is there a function that takes a class as a parameter and returns True or False depending on the existence of its children classes? Can it be possible in principle?

class A:
    pass

class B(A):
    pass

has_children(A)  # should return True
has_children(B)  # should return False

I would like to know a solution without access to globals(), locals(), vars().

Fomalhaut
  • 8,590
  • 8
  • 51
  • 95
  • Just for references, I have just posted a solution working with old style Python 2 classes (no __subclasses__ method available) under the [duplicate question](https://stackoverflow.com/a/46893520/3545273) – Serge Ballesta Oct 23 '17 at 15:55

1 Answers1

3

You can use the __subclasses__ method:

def has_children(cls):
    return bool(cls.__subclasses__())

This method is only defined for "new-style" classes (inherit from object in Python 2, default in Python 3).

jmd_dk
  • 12,125
  • 9
  • 63
  • 94