Search code examples
pythonconfiguration-filespython-sphinx

How do I read conf.py setting in Sphinx extension node?


from docutils.parsers.rst.directives.images import Figure
class MyFigure(Figure):
    def run(self):
        # here I need to read the 'thumbnails_folder' setting
        pass

def setup(app):
    app.add_config_value('thumbnails_folder', '_thumbnails', 'env')

How can I access the config value in .run()? I read sources of Sphinx-contrib, but did not see things done in my way, so they accessed conf.py the way I can't. Or should I do it in a different manner?

All I want to do is translate this

.. figure:: image/image.jpg

into this:

.. image:: image/thumbnails/image.jpg
   :target: image/image.jpg

Here's the extension code

(the thumbnail is generated with PIL). And also put the :target: into downloadable files (As I see, only builder instances can do this).


Solution

  • The build environment holds a reference to the Config object. Configuration variables can be retrieved from this object:

    def run(self):
        env = self.state.document.settings.env  # sphinx.environment.BuildEnvironment 
        config = env.config                     # sphinx.config.Config
        folder = config["thumbnails_folder"] 
        ...