P
P
pcdesign2021-08-11 16:28:10
Python
pcdesign, 2021-08-11 16:28:10

How to get a list of all classes from the current file?

For example, here's a file:

class A:
    pass


class B:
    pass


class C:
    pass


def get_all_classes_in_file():
    ''' Как добраться до всех классов, которые в этом файле лежат?'''


How to get a list of all classes?
If completely in the forehead, then like this:
import pyclbr
print(pyclbr.readmodule(__name__).keys())

It will just give the class names as a string, not as an object that can be accessed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-08-11
@pcdesign

You need to know the name of the module. For the main script (which you directly execute) it will be '__main__'. EMNIP this name can be learned from the magic variable __name__.

import sys

def enum_classes(module_name: str = __name__):
  module = sys.modules[module_name]
  return [v for v in vars(module).values() if type(v) is type and v.__module__ == module_name]

The first part of the condition will filter out everything except classes. The second one, in theory, will weed out what got into the namespace through imports like "from X import Y".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question