Optional and Union
- Python course
- Advanced
- Lesson 8/83
- 5 min
Learn optional types with Optional and Union.
Optional and Union
Sometimes a value is either a specific type or None. Optional declares that: Optional[int] means either int or None.
When one of two different types is needed, use Union: Union[int, str] accepts either an integer or a string.
from typing import Optional, Union
def find(id: int) -> Optional[str]:
if id == 1:
return "Ayşe"
return None
def parse(value: Union[int, str]) -> int:
return int(value)Python 3.10+ also allows the short int | str and int | None syntax; this lesson uses the typing module.
None safety and defaults
Before using a value from a function returning Optional[int], you should check for None. Otherwise calls like None.upper() raise an error.
Example: name = find(2) may return None. Guard with if name is not None:; otherwise use a default string.
With Union you list several types; the order does not matter, but pick a logical one for readability.
Practice Optional-returning find function
Write find(id: int) -> Optional[str]. If id == 1 return "Ayşe"; otherwise return None. Import Optional from typing. Call print(find(1)) and print(find(2)).
Starter code
# import Optional from typing
# find(id) -> Optional[str]: if id 1 return "Ayşe", else None
# print the result of find(1) and find(2)Sample solution
from typing import Optional
def find(id: int) -> Optional[str]:
if id == 1:
return "Ayşe"
return None
print(find(1))
print(find(2))Expected output
Ayşe None
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Import Optional
from typing import ____
def find(id: int) -> Optional[str]:
return None
from typing import Optional
def find(id: int) -> Optional[str]:
return None
Explanation: Optional comes from the typing module; it declares the None possibility.
2 Match the Optional and Union uses
| Term | Meaning |
|---|---|
Optional[int] |
int or None |
Union[int, str] |
int or str |
int | str |
Short syntax (3.10+) |
if v is not None |
None check |
3 Which value is VALID for Optional[str]?
- Only a string
- Only None
- Any type
- String or None Correct answer
Explanation: Optional[str] accepts str or None; both are valid.