iHnR
iHnR

Reputation: 495

Define type of optional function argument

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?

Upvotes: 0

Views: 93

Answers (1)

BeneSim
BeneSim

Reputation: 90

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

Upvotes: 1

Related Questions