Load Sphinx environment.pickle and List all Labels#

In order to come up with a reliable and standardized way of referring to document sections and document it in MySt and Markdown for Sphinx Cheatsheet, I went down a pretty deep rabbit hole of Sphinx label manipulations.

Ultimately, I decided to use the {ref} and {doc} MyST roles, primarly, in combination with the sphinx.ext.autosectionlabel extension [1]

To better understand what labels were being generated by the extension and how, I decided to find out how to list all labels Sphinx had in store.

Reading a bit around I stumbled upon a thread on StackOverflow which touched upon this. After playing around a bit, I managed to load environment.pickle and list the labels in the std domain.

1import pickle
3envfile = open('./_build/.doctrees/environment.pickle','rb')
4environ = pickle.load(envfile)
5elabels = environ.domaindata['std']['labels']
7for k,v in elabels.items():
8    # docname, (nodeid, title)
9    print(f"{k}: {v}")

⚠️ In case you’re using the sphinx-sitemap extension, you won’t be able to explore the environment.pickle as easily due to errors while loading it [2]. Remove it from your extensions and re-build; the errors for pickle.load will disappear.


Once you’re done reading this article, you can continue by having a look at the related content I’ve linked below.