使用“from foo import *”时加载的内容

时间:2016-05-17 18:21:00

标签: python python-2.7

如何列出调用/b时导入的内容。我已经尝试过sys.modules.keys()但是这个提供了更多的低级数据类型。

2 个答案:

答案 0 :(得分:4)

您应该在没有foo的情况下导入*,这样您就可以dir使用foo获取所有名称:

import foo
print dir(foo)

答案 1 :(得分:2)

作为一般Python规则,运行from foo import *被认为是坏样式(非pythonic),因为它污染了命名空间。

我对你的问题进行了一些思考,这就是我想出来的。使用iPython方便的%paste魔术功能将以下内容复制/粘贴到iPython中,或将其保存到脚本中并直接运行:

import pkgutil

def list_all_modules(top_level_package):
    modnames = []
    package = top_level_package
    prefix = package.__name__ + "."
    for importer, modname, ispkg in pkgutil.iter_modules(package.__path__, prefix):
        modnames.append(modname)
        if ispkg:
            module = __import__(modname, fromlist="dummy")
            recurse_modnames = list_all_modules(module)
            modnames += recurse_modnames
    return modnames

现在您可以导入模块/库foo,将其传递给此函数,并返回包str下所有可用模块/子模块的列表(foo个对象) 。像这样:

modnames = list_all_modules(foo)
print modnames

作为测试,我会在html5lib库提供here

In [2]: from pprint import pprint

In [3]: import html5lib

In [4]: modnames = list_all_modules(html5lib)

In [5]: pprint(modnames)

['html5lib.constants',
 'html5lib.filters',
 'html5lib.filters._base',
 'html5lib.filters.alphabeticalattributes',
 'html5lib.filters.inject_meta_charset',
 'html5lib.filters.lint',
 'html5lib.filters.optionaltags',
 'html5lib.filters.sanitizer',
 'html5lib.filters.whitespace',
 'html5lib.html5parser',
 'html5lib.ihatexml',
 'html5lib.inputstream',
 'html5lib.sanitizer',
 'html5lib.serializer',
 'html5lib.serializer.htmlserializer',
 'html5lib.tokenizer',
 'html5lib.treeadapters',
 'html5lib.treeadapters.sax',
 'html5lib.treebuilders',
 'html5lib.treebuilders._base',
 'html5lib.treebuilders.dom',
 'html5lib.treebuilders.etree',
 'html5lib.treebuilders.etree_lxml',
 'html5lib.treewalkers',
 'html5lib.treewalkers._base',
 'html5lib.treewalkers.dom',
 'html5lib.treewalkers.etree',
 'html5lib.treewalkers.genshistream',
 'html5lib.treewalkers.lxmletree',
 'html5lib.treewalkers.pulldom',
 'html5lib.trie',
 'html5lib.trie._base',
 'html5lib.trie.datrie',
 'html5lib.trie.py',
 'html5lib.utils']

这绝对感觉像是一种非pythonic方式,但如果有人有更好的方法,请告诉我。 :)