[Python] How does "MaybeNone" (also known as "The Any Trick") work in Python type hints?

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    In typestubs for the Python standard library I noticed a peculiar type called MaybeNone pop up, usually in the form of NormalType | MaybeNone. For example, in the sqlite3-Cursor class I find this:

    class Cursor:
    # May be None, but using `| MaybeNone` (`| Any`) instead to avoid slightly annoying false positives.
    @property
    def description(self) -> tuple[tuple[str, None, None, None, None, None, None], ...] | MaybeNone: ...


    The definition of this MaybeNone is given as:

    # Marker for return types that include None, but where forcing the user to
    # check for None can be detrimental. Sometimes called "the Any trick". See
    # CONTRIBUTING.md for more information.
    MaybeNone: TypeAlias = Any # stable


    (I could not find additional information in the CONTRIBUTING.md, which I assume to be this one.)

    I understand the intention of marking a return type in such a way that a user is not forced to null check in cases where the null is more of a theoretical problem for most users. But how does this achieve the goal?


    1. SomeType | Any seems to imply that the return type could be anything, when what I want to say is that it can be SomeType or in weird cases None, so this doesn't seem to express the intent.


    2. MyPy already allows superfluous null-checks on variables that can be proven not to be None even with --strict (at least with my configuration?) so what does the special typing even accomplish as compared to simply doing nothing?

    Continue reading...

Compartilhe esta Página