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

如何在Python函数文档字符串中实现换行显示?

Python函数文档字符串换行问题解决方法

你的问题是函数文档字符串在IDE悬停查看时,多行内容会连成一串无法正常换行。这主要是因为文档字符串的格式不符合IDE的解析规则,以下是具体的解决方案:

调整reStructuredText风格文档的缩进与格式

你当前使用的是带:param:标签的reStructuredText风格文档字符串,想要换行生效,需要注意两点:

  1. 换行后的内容要和参数描述的第一行开头对齐,而非随意缩进
  2. 用空行分隔不同的逻辑段落(比如描述和代码示例)

修改后的代码示例:

from pandas import PandasDataFrame
def calculate_input_types(price_df: PandasDataFrame, calculate_all: bool = True, *, input_type: dict) -> PandasDataFrame:
    """
    :param price_df: Dataframe containing Open, Close, High, Low, Volume price data.
    :param calculate_all: Boolean value True or False, if True function calculates all possible input types (HL2, HLC3, OHLC4, HLCC4).
        If False, function calculates only chosen input types, and you must pass a dictionary via `input_type`.
    :param input_type: Optional argument, mandatory if calculate_all is set to False. 
        A dictionary should use input types as keys, with a one-hot encoded value of 1 if the input type is to be calculated,
        or 0 if it shouldn't be calculated.
        
        Example:
        ```python
        input_type = {
            'HL2': 1,
            'HLC3': 1,
            'OHLC4': 0,
            'HLCC4': 1
        }
        ```
        This input will calculate only HL2, HLC3 and HLCC4 (since they're set to 1), while OHLC4 is skipped.
    :return: Dataframe with calculated input types.
    """
    return 'apple'

切换为更易解析的文档风格

如果调整格式后仍有问题,可以尝试Google或NumPy风格的文档字符串,这些风格结构更清晰,IDE(如PyCharm、VS Code)对其解析支持更好:

Google风格示例

from pandas import PandasDataFrame
def calculate_input_types(price_df: PandasDataFrame, calculate_all: bool = True, *, input_type: dict) -> PandasDataFrame:
    """Calculates specified input types from price data.

    Args:
        price_df: Dataframe containing Open, Close, High, Low, Volume price data.
        calculate_all: Boolean value. If True, calculates all possible input types (HL2, HLC3, OHLC4, HLCC4).
            If False, calculates only chosen input types, and `input_type` must be provided.
        input_type: Optional dict, required if `calculate_all` is False.
            Keys are input type names, values are 1 (calculate) or 0 (skip).
            
            Example:
            ```python
            input_type = {
                'HL2': 1,
                'HLC3': 1,
                'OHLC4': 0,
                'HLCC4': 1
            }
            ```
            This will compute HL2, HLC3 and HLCC4, skipping OHLC4.

    Returns:
        Dataframe with calculated input types.
    """
    return 'apple'

额外注意事项

  • 文档字符串里的输入类型名称(如HL2)要加单引号,避免被IDE识别为未定义变量
  • 代码示例用```python包裹,能让IDE正确保留格式和换行
  • 不同IDE的解析规则略有差异,若仍有问题,可以检查IDE的Python文档解析设置(比如VS Code需要安装Python插件并启用文档字符串支持)

内容的提问来源于stack exchange,提问作者Jakub Szurlej

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:55:15