[Python] Type-hinting parameters with a sentinel value as the default

Discussão em 'Python' iniciado por Stack, Junho 13, 2025.

  1. Stack

    Stack Membro Participativo

    I currently use this strategy when I cannot assign default arguments in a function's signature and/or None already has meaning.

    from typing import Optional

    DEFAULT = object()


    # `None` already has meaning.
    def spam(ham: Optional[list[str]] = DEFAULT):
    if ham is DEFAULT:
    ham = ['prosciutto', 'jamon']
    if ham is None:
    print('Eggs?')
    else:
    print(str(len(ham)) + ' ham(s).')


    Error:

    Failed (exit code: 1) (2607 ms)

    main.py:7: error: Incompatible default for argument "ham" (default has type "object", argument has type "Optional[List[str]]")
    Found 1 error in 1 file (checked 1 source file)

    • How do I type-hint ham without getting errors in mypy? or
    • What strategy should I use instead of DEFAULT = object()?

    Continue reading...

Compartilhe esta Página