查找在模块中明确定义的函数(python) [英] Find functions explicitly defined in a module (python)

查看:178
本文介绍了查找在模块中明确定义的函数(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我知道您可以使用dir()方法列出模块中的所有内容,但是有什么方法只能查看该模块中定义的功能吗?例如,假设我的模块如下所示:

Ok I know you can use the dir() method to list everything in a module, but is there any way to see only the functions that are defined in that module? For example, assume my module looks like this:

from datetime import date, datetime

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

即使我使用inspect()过滤掉了内置函数,我仍然剩下任何导入的内容.例如,我会看到:

Even if i use inspect() to filter out the builtins, I'm still left with anything that was imported. E.g I'll see:

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

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

有什么办法可以排除进口?还是找出模块中定义的另一种方法?

Is there any way to exclude imports? Or another way to find out what's defined in a module?

推荐答案

您是否正在寻找类似的东西?

Are you looking for something like this?

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'以避免混淆(我们在这里处理函数,而不是方法).

Changed variable names from 'meth' to 'func' to avoid confusion (we're dealing with functions, not methods, here).

这篇关于查找在模块中明确定义的函数(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆