如何获取模块中定义但未导入的所有类?

发布于 2024-10-28 20:07:32 字数 711 浏览 4 评论 0原文

我已经看到了以下问题,但它并没有完全满足我的要求: 如何获取 Python 中当前模块内所有类的列表?

特别是,我不希望导入类,例如,如果我有以下模块:

from my.namespace import MyBaseClass
from somewhere.else import SomeOtherClass

class NewClass(MyBaseClass):
    pass

class AnotherClass(MyBaseClass):
    pass

class YetAnotherClass(MyBaseClass):
    pass

如果我使用 cls成员= spect.getmembers(sys.modules[__name__], inform.isclass) 就像链接问题中接受的答案所示,它将返回 MyBaseClassSomeOtherClass除了本模块中定义的 3 个之外。

如何只获取 NewClassAnotherClassYetAnotherClass

I've already seen the following question but it doesn't quite get me where I want: How can I get a list of all classes within current module in Python?

In particular, I do not want classes that are imported, e.g. if I had the following module:

from my.namespace import MyBaseClass
from somewhere.else import SomeOtherClass

class NewClass(MyBaseClass):
    pass

class AnotherClass(MyBaseClass):
    pass

class YetAnotherClass(MyBaseClass):
    pass

If I use clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass) like the accepted answer in the linked question suggests, it would return MyBaseClass and SomeOtherClass in addition to the 3 defined in this module.

How can I get only NewClass, AnotherClass and YetAnotherClass?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

木森分化 2024-11-04 20:07:32

检查类的 __module__ 属性以找出它是在哪个模块中定义的。

Inspect the __module__ attribute of the class to find out which module it was defined in.

┾廆蒐ゝ 2024-11-04 20:07:32

对于回答这样一个老问题,我深表歉意,但我对使用此解决方案的检查模块感到不舒服。我在某处读到在生产中使用不安全。

初始化 a 中的所有类模块转换为列表中的无名对象

请参阅Antonis Christofides 对答案 1 的评论

我得到了测试对象是否是一个类的答案
如何检查变量是否是是否有类?

所以这是我的免检查解决方案

def classesinmodule(module):
    md = module.__dict__
    return [
        md[c] for c in md if (
            isinstance(md[c], type) and md[c].__module__ == module.__name__
        )
    ]

classesinmodule(modulename)

I apologize for answering such an old question, but I didn't feel comfortable using the inspect module for this solution. I read somewhere that is wasn't safe to use in production.

Initialize all the classes in a module into nameless objects in a list

See Antonis Christofides comment to answer 1.

I got the answer for testing if an object is a class from
How to check whether a variable is a class or not?

So this is my inspect-free solution

def classesinmodule(module):
    md = module.__dict__
    return [
        md[c] for c in md if (
            isinstance(md[c], type) and md[c].__module__ == module.__name__
        )
    ]

classesinmodule(modulename)
无人问我粥可暖 2024-11-04 20:07:32

您可能还想考虑使用标准库中的“Python 类浏览器”模块:
http://docs.python.org/library/pyclbr.html

因为它没有它实际上执行有问题的模块(它执行朴素的源检查),有一些它不太正确理解的特定技术,但对于所有“正常”类定义,它会准确地描述它们。

You may also want to consider using the "Python class browser" module in the standard library:
http://docs.python.org/library/pyclbr.html

Since it doesn't actually execute the module in question (it does naive source inspection instead) there are some specific techniques it doesn't quite understand correctly, but for all "normal" class definitions, it will describe them accurately.

小伙你站住 2024-11-04 20:07:32

我使用了以下内容:

# Predicate to make sure the classes only come from the module in question
def pred(c):
    return inspect.isclass(c) and c.__module__ == pred.__module__
# fetch all members of module __name__ matching 'pred'
classes = inspect.getmembers(sys.modules[__name__], pred)

我不想在中键入当前模块名称

I used the below:

# Predicate to make sure the classes only come from the module in question
def pred(c):
    return inspect.isclass(c) and c.__module__ == pred.__module__
# fetch all members of module __name__ matching 'pred'
classes = inspect.getmembers(sys.modules[__name__], pred)

I didn't want to type the current module name in

夏有森光若流苏 2024-11-04 20:07:32
from pyclbr import readmodule

clsmembers = readmodule(__name__).items()
from pyclbr import readmodule

clsmembers = readmodule(__name__).items()
傾旎 2024-11-04 20:07:32

保持简单的解决方案:

> python.exe -c "import unittest"
> python.exe -c "from .panda_tools import *"

命令行帮助:-c cmd:程序以字符串形式传入(终止选项列表)

如果 Python 尝试加载,如果未找到,则会给出以下错误类型:

ModuleNotFoundError: No module named 'unittest'
ImportError: attempted relative import with no known parent package

The Keep it simple solution:

> python.exe -c "import unittest"
> python.exe -c "from .panda_tools import *"

Command line help: -c cmd : program passed in as string (terminates option list)

If Python will attempt to loading, if not found gives these error types:

ModuleNotFoundError: No module named 'unittest'
ImportError: attempted relative import with no known parent package
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文