0

How do I use type checking in a function that has optional parameters? For instance:

def do_something_cool(number1: int, letter1: str, seed=None: (None, int) )-> str:
    return 

will fail because of (None, int). What is the correct syntax for this?

CiaranWelsh
  • 7,014
  • 10
  • 53
  • 106
  • Right now your code fails because you have mismatched parentheses (you never close the parameter list). – h4z3 Aug 07 '19 at 08:51

1 Answers1

1

With most type checkers the following works without explicitly saying that the value is nonable:

def do_something_cool(number1: int, letter1: str, seed: int = None) -> str:
    return 

However, you can also explicitly specify that the value is nonable:

from typing import Optional

def do_something_cool(number1: int, letter1: str, seed: Optional[int] = None) -> str:
    return

Big warning here: typing.Optional actually means Nonable and has nothing to do with the fact that your value has a default value (so it does not mean "optional"). See this discussion. One way to remember it is to think of Optional as applying to the type, not to the value.

PEP484 was previously recommending the implicit writing, but now recommends that you explicitly states Optional when your value is Nonable. See here.

smarie
  • 4,568
  • 24
  • 39