繁体   English   中英

如何从 python 的模块中列出全局命名空间的内容

[英]How can you list the contents of the global namespace from within a module in python

在 python 中,您可以键入 dir() 来获取全局命名空间中的项目列表,但该列表很丑陋,它包括公共和私有对象。 我想写一个漂亮的 function(说pretty )。 我的 function 将存在于一个模块中。

当我调用pretty(dir())时,我会漂亮地打印模块中的对象。 相同的pretty(sorted(globals())) 如何获取全局命名空间中的对象名称列表(从模块内),以便进行美化?

如果这很重要,我正在使用python3。

编辑:返回的前两个答案与我在包含pretty的模块中的控制代码有关。 那不是我想做的。 我的目标是获得类似以下的体验。

>>> foo = create_something()
>>> bar = create_something_else()
>>> create_lots_more_stuff()
>>> # Hmmmm I'd like to see a list of all the things I have created in my interactive python session.
>>> pretty(dir())
foo     bar
baz     qux
etc     etc_etc

与其编写 function 来过滤dir()结果,不如使用属性__all__和/或__dir__让您的模块显式地公开导出命名空间,如PEP 0562中所述。

# lib.py
deprecated_names = ["old_function", ...]
__all__ = ["new_function_one", "new_function_two", ...]

def new_function_one(arg, other):
   ...

def new_function_two(arg, other):
    ...

def __dir__():
    return sorted(__all__ + deprecated_names)

用法:

# main.py
import lib

dir(lib)  # prints ["new_function_one", "new_function_two", "old_function", ...]

注意:模块级__dir__钩子需要 Python 3.7+。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM