You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Sphinx仅记录Python模块字典常量的项内容?

Solution: Add a Docstring to the Dictionary and Use Autodata with Proper Options

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:09:12