0

In Python3 I can do :

# Function with string as input
def function(argument: str):
    return argument

But I cannot:

# Function with optional input
def function(argument='default': str):
    return argument

What would be the correct syntax to define the type of an optional argument?

iHnR
  • 125
  • 7
  • 1
    Does this answer your question? [Adding default parameter value with type hint in Python](https://stackoverflow.com/questions/38727520/adding-default-parameter-value-with-type-hint-in-python) – azro Apr 12 '20 at 10:00

1 Answers1

1

Just swap the position of the default value and the type

# Function with optional input
def function(argument: str = "default"):
    return argument

/EDIT If you really want to express an optional value and not just a default value you could use something like this

from typing import Optional

# Function with optional input
def function(argument: Optional[str] = None):
    return argument
BeneSim
  • 80
  • 5
  • You actually managed to answer my follow up question as well. Thanks for the quick answer :) – iHnR Apr 12 '20 at 10:15