【问题标题】:Is it possible to make the imports within `__init__.py` visible for python `help()` command?是否可以让 python `help()` 命令看到`__init__.py` 中的导入?
【发布时间】:2021-12-01 01:07:05
【问题描述】:

假设我有一个模块:

mymodule/example.py:

def add_one(number):
    return number + 1

还有mymodule/__init__.py:

from .example import *

foo = "FOO"

def bar():
    return 1

现在我看到了mymodule的根函数:

>>> import mymodule
>>> mymodule.add_one(3)
4
>>> mymodule.foo
'FOO'

另外,我看到导入的 add_onedir 以及 example

>>> dir(mymodule)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'add_one', 'bar', 'example', 'foo']

但是当我输入help(mymodule) 时,我只看到examplefoobar,而不是导入的add_one

Help on package mymodule:

NAME
    mymodule

PACKAGE CONTENTS
    example

FUNCTIONS
    bar()

DATA
    foo = 'FOO'

但是我可以调用add_one() 作为mymodule 的根函数。是否可以在帮助中看到它作为根函数?

【问题讨论】:

    标签: python python-import python-packaging


    【解决方案1】:

    来自help()的源码(docmodule under pydoc.py)

            for key, value in inspect.getmembers(object, inspect.isroutine):
                # if __all__ exists, believe it.  Otherwise use old heuristic.
                if (all is not None or
                    inspect.isbuiltin(value) or inspect.getmodule(value) is object):
                    if visiblename(key, all, object):
                        funcs.append((key, value))
    

    重要的部分是inspect.getmodule(value) is object),这是删除不直接属于对象本身的值的地方

    你可以添加这一行

    __all__ = ['bar', 'add_one', 'FOO']
    

    到您的__init__.py 文件,这样帮助功能将确保将这些对象包含在帮助中

    请记住,如果您这样做,那么您未包含在此列表中的任何内容都不会被包含在内

    【讨论】:

    • 谢谢!我认为__all__ 只是定义了当我执行from mymodule import * 时将导入的内容。现在我看到它也会影响逻辑,help() 的组成方式。好的。
    猜你喜欢
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 2020-03-02
    相关资源
    最近更新 更多