在 Python 模块上子类化 __dir__

Subclassing __dir__ on a Python module

从 Python 3.7 开始,可以在模块上定义 __dir__()。但是,如果您想获取 dir(module) 的“正常”输出并从中添加或删除怎么办?

例如,我想做这样的事情:

def __dir__():
    dir_out = super().__dir__()[:]  # does not work
    dir_out.pop('Optional')  # get rid of the typing imports
    return dir_out

显然因为模块不是正常的 class,所以 super() 调用不起作用。但是还有别的办法吗?

使用 globals() 命令获取通常出现在目录中的内容:

def __dir__():
    dir_out = list(globals()) 
    dir_out.pop('Optional')  # get rid of the typing imports
    return dir_out