0

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. I found out that you can define one type of return using this example (-> 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

4
  • 2
    You probably don't want a function with return type Union[str, list] in the first place. (As an aside, docstrings are not involved here at all.) Commented Jun 15, 2022 at 16:05
  • As per comment above, the syntax is Union[str, list] but it is a bad idea to have a function that returns one of two unrelated types - that will complicate all the other code that has to call that function. Avoiding that will probably lead to a better design. Commented Jun 15, 2022 at 16:17
  • And as referenced -- these are type hints, which are a completely different thing than docstrings. Commented Jun 15, 2022 at 16:21

2 Answers 2

1
from typing import Union, List

def function(x, y) -> Union[str, List[int]]:
  if x == 1:
    return "test"
  return [1, 2]
Sign up to request clarification or add additional context in comments.

Comments

0

Depending on your Python version, there are multiple ways this can be epxressed:

  • Prior to 3.9:

    from typing import Union, List
    def foo() -> Union[str, List]: pass 
    
  • Since Python v. 3.9 you can also write:

     from typing import Union
     def foo() -> Union[str, list]: pass
    
  • Since Python v. 3.10 you can also write:

     def foo() -> str | list: pass
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.