Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

The `X | None` type union

`X | None` describes a value of type `X` or the value `None`. In `-> str | None`, it describes a function's return value, not a default.

Version: Python 3.12

Syntax

X | None

In Python 3.12, the type union X | None combines X with the type whose only value is None. This syntax was added in Python 3.10. In str | None, | constructs a type union; it does not perform bitwise OR on integers. As a type hint, X | None is equivalent to typing.Optional[X] and typing.Union[X, None].

The parameter annotation value: str | None allows callers to pass None, but it does not let them omit the argument: no default is specified. Writing value: str | None = None also supplies a default. Python itself does not enforce these annotations at runtime.

In the example, -> str | None describes the return value of the parse_args helper. The method argparse.ArgumentParser.parse_args returns an argparse.Namespace, while the helper returns just its profile attribute. Check profile is None before using string methods: '' is still a string and is not a missing value.

Examples

import argparse


def parse_args(argv: list[str]) -> str | None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--profile", default=None)
    return parser.parse_args(argv).profile


for argv in ([], ["--profile", "dev"], ["--profile="]):
    profile = parse_args(argv)
    if profile is None:
        print("No profile provided")
    else:
        print(f"Profile: {profile!r}")

Result

No profile provided
Profile: 'dev'
Profile: ''

The three calls show an omitted `--profile` option, the value `'dev'`, and an explicitly supplied empty string `''`.

Related lessons

  • Python · Lesson 34 · Advanced · Version: 5

Sources