查找模块中显式定义的函数(Python)

24 投票
6 回答
10165 浏览
提问于 2025-04-15 12:47

好的,我知道你可以用 dir() 方法来列出一个模块里的所有东西,但有没有办法只看到这个模块里定义的函数呢?比如,假设我的模块长这样:

from datetime import date, datetime

def test():
    return "This is a real method"

即使我使用 inspect() 来过滤掉内置的内容,我还是会看到任何被导入的东西。例如,我会看到:

['date', 'datetime', 'test']

有没有办法排除这些导入的内容?或者有没有其他方法可以找出一个模块里定义了什么?

6 个回答

2

你可以查看一下这个函数的 __module__ 属性。我之所以说“函数”,是因为方法通常是属于某个类的;-)

顺便提一下,类其实也有 __module__ 属性。

5

下面这个怎么样:

grep ^def my_module.py
32

你是在找这样的东西吗?

import sys, inspect

def is_mod_function(mod, func):
    return inspect.isfunction(func) and inspect.getmodule(func) == mod

def list_functions(mod):
    return [func.__name__ for func in mod.__dict__.itervalues() 
            if is_mod_function(mod, func)]


print 'functions in current module:\n', list_functions(sys.modules[__name__])
print 'functions in inspect module:\n', list_functions(inspect)

编辑:把变量名从'meth'改成'func',这样可以避免混淆(我们这里讨论的是函数,不是方法)。

撰写回答