In Python, how do I get the list of classes defined within a particular file?

旧巷老猫 提交于 2020-12-30 08:11:25

问题


If a file myfile.py contains:

class A(object):
  # Some implementation

class B (object):
  # Some implementation

How can I define a method so that, given myfile.py, it returns [A, B]?

Here, the returned values for A and B can be either the name of the classes or the type of the classes.

(i.e. type(A) = type(str) or type(A) = type(type))


回答1:


You can get both:

import importlib, inspect
for name, cls in inspect.getmembers(importlib.import_module("myfile"), inspect.isclass):

you may additionally want to check:

if cls.__module__ == 'myfile'



回答2:


In case it helps someone else. Here is the final solution that I used. This method returns all classes defined in a particular package.

I keep all of the subclasses of X in a particular folder (package) and then, using this method, I can load all the subclasses of X, even if they haven't been imported yet. (If they haven't been imported yet, they cannot be accessible via __all__; otherwise things would have been much easier).

import importlib, os, inspect

def get_modules_in_package(package_name: str):
    files = os.listdir(package_name)
    for file in files:
        if file not in ['__init__.py', '__pycache__']:
            if file[-3:] != '.py':
                continue

            file_name = file[:-3]
            module_name = package_name + '.' + file_name
            for name, cls in inspect.getmembers(importlib.import_module(module_name), inspect.isclass):
                if cls.__module__ == module_name:
                    yield cls



回答3:


It's a bit long-winded, but you first need to load the file as a module, then inspect its methods to see which are classes:

import inspect
import importlib.util

# Load the module from file
spec = importlib.util.spec_from_file_location("foo", "foo.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)

# Return a list of all attributes of foo which are classes
[x for x in dir(foo) if inspect.isclass(getattr(foo, x))]


来源:https://stackoverflow.com/questions/55067166/in-python-how-do-i-get-the-list-of-classes-defined-within-a-particular-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!