简体   繁体   English

Python Docstring - 函数的两种不同类型的参数

[英]Python Docstring - two different types of arguments of a function

I tried to make my function-description look beautiful but it didn't work.我试图让我的功能描述看起来很漂亮,但是没有用。 The problem is that I have two types of returns: a list and a string.问题是我有两种类型的返回:一个列表和一个字符串。 Then you hover on functions vscode shows the returns of the functions like this .然后你将鼠标悬停在函数上,vscode 会显示函数的返回,如下所示 I found out that you can define one type of return using this example (-> str):我发现您可以使用此示例(-> str)定义一种返回类型:

def function(x, y) -> str:
  string = "test"
  return string

But let's say I have tow diffrent return in my code:但是假设我的代码中有两个不同的返回:

def function(x, y):
  if x == 1:
    string = "test"
    return string
  else:
    list = [1, 2]
    return list

How to assign two different types of returns to that function?如何为该函数分配两种不同类型的返回? here is another example是另一个例子

from typing import Union, List

def function(x, y) -> Union[str, List[int]]:
  if x == 1:
    return "test"
  return [1, 2]

Depending on your Python version, there are multiple ways this can be epxressed:根据您的 Python 版本,可以通过多种方式对此进行表达:

  • Prior to 3.9:在 3.9 之前:

     from typing import Union, List def foo() -> Union[str, List]: pass
  • Since Python v. 3.9 you can also write:从 Python v. 3.9 开始,您还可以编写:

     from typing import Union def foo() -> Union[str, list]: pass
  • Since Python v. 3.10 you can also write:从 Python v. 3.10 开始,您还可以编写:

     def foo() -> str | list: pass

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

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