简体   繁体   English

在 Python 中的 function 定义上声明多个返回类型

[英]Declaring multiple return types on function definition in Python

I've being having some trouble when commentating functions or methods that returns multiple variables as example:我在评论返回多个变量的函数或方法时遇到了一些麻烦,例如:

def separate_dfs(dataframe: pd.DataFrame) -> ?:

    there_is_only_one_column = False
    df1 = dataframe["column1"]
    
    try:
       df2 = dataframe["column2"]
    except KeyError:
       df2 = None
       there_is_only_one_column = True
    
    return df1, df2, there_is_only_one_column

In the example, the returned variables can be of 3 types: pd.DataFrame, None and bool.在示例中,返回的变量可以是 3 种类型:pd.DataFrame、None 和 bool。 But i couldn't find anywhere in the pep8 guide that explained how to handle that.但是我在 pep8 指南中找不到任何解释如何处理的地方。

I also don't know what to do when one variable can be more than one type (like df2 that might be pd.DataFrame or None).我也不知道当一个变量可以是不止一种类型时该怎么办(比如 df2 可能是 pd.DataFrame 或 None)。

The exact return type would be确切的返回类型是

from typing import Optional, Tuple
def separate_dfs(dataframe: pd.DataFrame) -> Tuple[pd.DataFrame, Optional[pd.DataFrame], bool]
...

When you are using Python > 3.8, You can use the builtin tuple to write your annotation.当您使用 Python > 3.8 时,您可以使用内置tuple来编写注释。 When you are using Python 3.10 you can write it even more compact as当您使用 Python 3.10 时,您可以将它写得更紧凑

def separate_dfs(dataframe: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame | None, bool]
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM