Junior
What is the Optional type annotation in Python?
sobes.tech AI
Answer from AI
Optional[T] in Python is a shorthand for Union[T, None]. It indicates that a variable, function parameter, or return value can be either of type T or None. It is used to explicitly specify the possibility of absence of a value.
Example usage:
# Function parameter annotation
def process_data(data: Optional[str]) -> Optional[int]:
if data is None:
return None
# Data processing logic
try:
return int(data)
except ValueError:
return None
# Variable annotation
user_id: Optional[int] = get_user_id()
| Usage | Description |
|---|---|
| Function parameter annotation | Indicates that the argument can be omitted or set to None. |
| Return value annotation | Shows that the function can return a value or None. |
| Variable annotation | Indicates that the variable can contain a value of the specified type or None. |
Using Optional improves code readability and helps static analysis tools (like MyPy) identify potential errors related to handling None.