Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

typing.Optional

Optional[T] allows either T or None and is equivalent to a union with None.

Version: Python 3.14; repository image, production runtime not attested

Syntax

amount: Optional[int]

Optional[T] allows either T or None and is equivalent to a union with None.

It describes the accepted values and does not give the parameter a default. A required parameter with this annotation still raises TypeError when omitted.

The example accepts None explicitly and preserves zero as a distinct value.

Examples

from typing import Optional
def display(amount: Optional[int]) -> str:
    return "missing" if amount is None else str(amount)
print(display(None), display(0))
try:
    display()
except TypeError:
    print("argument required")

Result

missing 0
argument required

The example accepts None explicitly and preserves zero as a distinct value.

Sources