【问题标题】:Python method return hint for method that can either return a tuple or single value可以返回元组或单个值的方法的 Python 方法返回提示
【发布时间】:2022-12-12 21:32:10
【问题描述】:

在我的 BatterSimulation 类中,我有一个静态方法,它返回 Tuple[pd.Dataframe, np.array] 或仅返回数据帧,具体取决于我是否在类内部使用该方法。

@staticmethod
def transform_schedule(schedule: List[dict], time_step: int,
                       offset_power: pd.DataFrame, internal_use: bool = True) -> ?:

...

    if internal_use:
      return schedule, schedule.state.values
    else:
      return schedule

我如何为此使用返回类型提示?这通常是这样做的,还是这种不好的做法?

我尝试了以下内容:

@staticmethod
def transform_schedule(schedule: List[dict], time_step: int,
                       offset_power: pd.DataFrame, internal_use: bool = True) -> Tuple[pd.DataFrame, np.array] or pd.DataFrame:

【问题讨论】:

  • 我宁愿将它更改为始终返回一个元组,如果不读取它,第二个值可能是None

标签: python python-3.x type-hinting


【解决方案1】:

你可以这样写:

Tuple[pd.DataFrame, np.array] | pd.DataFrame

或者

Union[Tuple[pd.DataFrame, np.array], pd.DataFrame]

同样在你的情况下,这个可能更好:

Tuple[pd.DataFrame, Optional[np.array]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 2023-02-19
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 2016-03-28
    • 2015-09-24
    • 1970-01-01
    相关资源
    最近更新 更多