Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've seen several functionalities in Sphinx that define a setup(app) function, for example the "Docstring preprocessing" functionalities of the autodoc extension.

I tried finding the API for setup(app) but the results haven't fully enlightened me. I found this brief explanation:

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.

There is also this explanation:

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.

And finally this explanation:

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.

So my question is if the only use of setup(app) in conf.py is connecting event handlers to Sphinx core events through Sphinx.connect(event, callback) function? Or am I missing something? Are all other uses of setup(app) restricted to writing custom extensions?

P.S. Adding confusion the setup reserved word is also used by "Setuptools integration", and searching the documentation there are several occurrences . I suppose this is an unrelated coincidence of using the same name.

like image 788
bad_coder Avatar asked Sep 02 '25 14:09

bad_coder


1 Answers

Both. You can use setup() in either your conf.py or a Sphinx extension which also happens to be a Python module. It's a Python thing. An example usage in Pyramid docs and you can find similar in Sphinx extensions. There's an example in the Sphinx docs, too:

# 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)

Now, you will have access to this function in jinja like so:

<div>
{{ my_func("some string") }}
</div>
like image 189
Steve Piercy Avatar answered Sep 05 '25 03:09

Steve Piercy