如何用Sphinx仅记录Python模块字典常量的项内容?
The issue you're facing happens because Sphinx's autodata directive falls back to showing the dict class's docstring when your module-level dictionary doesn't have its own docstring. To fix this and display only the dictionary's key-value pairs (plus helpful context if you want), follow these steps:
Step 1: Add a Docstring to the Dictionary
In your construct/core.py file, modify the possiblestringencodings dictionary definition to include a docstring. This replaces the default dict class docstring with your custom explanation, and Sphinx will prioritize this:
possiblestringencodings = dict( StringsAsBytes=1, ascii=1, utf8=1, utf_8=1, U8=1, utf16=2, utf_16=2, U16=2, utf_16_be=2, utf_16_le=2, utf32=4, utf_32=4, U32=4, utf_32_be=4, utf_32_le=4, ) """Mapping of string encoding names to their corresponding byte size indicators: - **1-byte encodings**: StringsAsBytes, ascii, utf8, utf_8, U8 - **2-byte encodings**: utf16, utf_16, U16, utf_16_be, utf_16_le - **4-byte encodings**: utf32, utf_32, U32, utf_32_be, utf_32_le """
Step 2: Update the Sphinx Directive
In your Read the Docs .rst file, keep using the autodata directive, but you can adjust options to control what's displayed:
Option A: Show Both Docstring and Dictionary Content
Use the directive without extra options to display your custom docstring followed by the full dictionary repr:
.. autodata:: construct.possiblestringencodings
Option B: Only Show the Dictionary Content
If you don't want the docstring and only need the key-value pairs, add the :no-docstring: option (available in Sphinx 4.0+):
.. autodata:: construct.possiblestringencodings :no-docstring:
Option C: Customize the Displayed Annotation
If you want to replace the default dict label with something more descriptive, use the :annotation: option:
.. autodata:: construct.possiblestringencodings :annotation: = Mapping of encodings to byte sizes
Step 3: Test the Build
Fork the repository, make the changes above, then run in the docs directory:
make html
Open the generated HTML files to verify that the dictionary's items are displayed instead of the dict constructor's docstring.
内容的提问来源于stack exchange,提问作者ArekBulski

