如何配置 Python 以便我可以直接从包中导入函数?

How to configure Python so that I can import a function directly from package?

假设我有一个像这样的包结构

pkg
   __init__.py
   module
      __init__.py
      a.py
      b.py

假设,a.py中有一个函数func。我想创建一个库,可以直接从 pkg 导入 func

from pkg import func

我怎样才能做到这一点?

您可以通过 __init__.py 进行配置。

pkg/__init__.py

from .module.a import func

这样,当访问 pkg 时,将加载 __init__.py,从而允许直接访问 pkg.func

这是documented:

A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The __init__.py file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported.