0

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.

Ali
  • 183
  • 1
  • 7
  • 2
    Does this answer your question? [How to access outer class from an inner class?](https://stackoverflow.com/questions/2024566/how-to-access-outer-class-from-an-inner-class) – JPI93 Sep 30 '20 at 11:32
  • No. The linked question is where you are in an inner class and want to access an outer class method. In my situation, you are not in the inner class, but you have an inner class object and want to access the class of its outer class. – Ali Sep 30 '20 at 11:42

1 Answers1

0

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):
    ...
AKX
  • 152,115
  • 15
  • 115
  • 172