Python: Get outter class off of an inner class object

129 Views Asked by At

I have a setup like below where B is an inner class and A is an outer class:

class A:
  # some A stuff
  class B:
    # Some B stuff

If I have a B instance:

b = B()

How can I get class A?

In other words, I want something like type(b) which normally gives class B but instead to get b's outer class A.

Edit

I have found __qualname__ with which if you do type(b). __qualname__ you get the string "A.B". Although close, I don't think from the string I can get the outer class itself.

1

There are 1 best solutions below

0
On

There's no reference to the "parent" class (since they're just namespaces that get assigned to the class object) unless you manually do something like

from enum import Enum
class A:
  class B(Enum):
    X = 1

A.B.parent = A

You can of course write a class decorator that iterates through all the members of the class it's decorated with, and if they're classes, annotates them with a property like that, bringing you to

from enum to Enum

@annotate_subclasses  # Implementation elided :)
class A:
  class B(Enum):
    ...