conf.py 中的 setup(app) 有什么用?

What are the uses of setup(app) in conf.py?

我在 Sphinx 中看到了几个定义 setup(app) 函数的功能,例如 autodoc 扩展的 "Docstring preprocessing" 功能。

我尝试为 setup(app) 找到 API,但结果并没有完全启发我。我找到了这个简短的解释:

Application API

Each Sphinx extension is a Python module with at least a setup() function. This function is called at initialization time with one argument, the application object representing the Sphinx process.

还有这样的解释:

Developing extensions for Sphinx

When sphinx-build is executed, Sphinx will attempt to import each module that is listed, and execute yourmodule.setup(app). This function is used to prepare the extension (e.g., by executing Python code), linking resources that Sphinx uses in the build process (like CSS or HTML files), and notifying Sphinx of everything the extension offers (such as directive or role definitions). The app argument is an instance of Sphinx and gives you control over most aspects of the Sphinx build.

最后是这个解释:

Sphinx core events

These events are known to the core. The arguments shown are given to the registered event handlers. Use Sphinx.connect() in an extension’s setup function (note that conf.py can also have a setup function) to connect handlers to the events.

所以我的问题是 conf.pysetup(app) 的唯一用途是将事件处理程序连接到 Sphinx core events through Sphinx.connect(event, callback) 函数吗?或者我错过了什么? setup(app) 的所有其他用途是否仅限于编写自定义扩展?

P.S。更让人困惑的是 setup 保留字也被 "Setuptools integration", and searching the documentation there are several occurrences 使用。我想这是使用相同名称的无关巧合。

两者都有。您可以在 conf.py 或恰好也是 Python 模块的 Sphinx 扩展中使用 setup()。这是一件 Python 的事情。还有一个example usage in Pyramid docs and you can find similar in Sphinx extensions. There's an example in the Sphinx docs

# The registration function
 def setup_my_func(app, pagename, templatename, context, doctree):
     # The template function
     def my_func(mystring):
         return "Your string is %s" % mystring
     # Add it to the page's context
     context['my_func'] = my_func

 # Your extension's setup function
 def setup(app):
     app.connect("html-page-context", setup_my_func)

现在,您将可以像这样在 jinja 中访问此功能:

<div>
{{ my_func("some string") }}
</div>