Search code examples
pythonpython-sphinx

How to programmatically generate some documentation from Python dictionary and insert it into .rst file using Sphinx


I am writing a configuration tool that automates the deployment of some monitoring dashboards. Each dashboard has a written description that is available in the tool, and can be found in the deployed dashboard. But we also have some functional documentation that repeats this description so end-users can read it outside of the code. So basically we have the following:

  1. description_mapping.py
dashboard_description_mapping = {"dashboard_1": "This dashboard achieves xyz"}
  1. README.rst
Templates
=========

Descriptions
------------

* **dashboard_1**
    
    This dashboard achieves xyz

I simplified the approach, in the real case we have many dashboard and descriptions that are all duplicated in the file description_mapping.py and in README.rst.

I would like to have the ability to be able to do some sort of command that gives me the following:

Templates
=========

Descriptions
------------

* **dashboard_1**
   
   .. magic_command: description_mapping.dashboard_description_mapping.get("dashboard_1")

Which would then render as if the description is automagically grabbed, and basically then I don't violate the DRY principle anymore.

Is this possible? I have searched a while, and came across this former question ,but this does not seem to achieve what I need:

  1. How to use Python to programmatically generate part of Sphinx documentation?
  2. Displaying dictionary data in Sphinx documentation

I would like to grab the string, not just print out the whole dictionary basically.

I tried to use existing functionality of ..autodoc, but this did not give me desired output but simply printed out the dictionary.


Solution

  • I actually figured out how to do it, I used the custom ..exec directive from: https://stackoverflow.com/a/10146415/8580574 and basically just printed how I wanted it formatted:

    .. exec::
        from title_desc_mappings import dashboard_description_mapping
        
        for key, value in dashboard_description_mapping.items():
            if key.startswith('dashboard'):
                print(f"* **{key}**\n\n")
      
                if value == '':
                    print("  No description available.\n")
                else:
                    print(f"  {value}\n")
    

    hope this helps someone else