Skip to content

Different behavior between Union and | in mypy when dealing with optionals #10499

Closed
@jevandezande

Description

@jevandezande

In the following two code examples, the first gives an error, while the latter does not. As I understand type1 | type2 is supposed to be an alias for Union[type1, type2] in python3.10 (hence the from __future__ import annotations).

from __future__ import annotations

def f(a: int | str = None):
    pass

error: Incompatible default for argument "a" (default has type "None", argument has type "Union[int, str]")

from typing import Union

def f(a: Union[int, str] = None):
    pass

As of PEP 484, non-explicit optional is discouraged. Is this the correct behavior, or a bug?

Your Environment

  • python = 3.9.1
  • mypy = 0.812

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-pep-604PEP 604 (union | operator)

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions