Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implicit optional doesn't work with new union syntax #10987

Closed
DetachHead opened this issue Aug 17, 2021 · 3 comments
Closed

implicit optional doesn't work with new union syntax #10987

DetachHead opened this issue Aug 17, 2021 · 3 comments
Labels
bug mypy got something wrong

Comments

@DetachHead
Copy link
Contributor

from typing import Union


def foo(value: int | str = None) -> None: # error: Incompatible default for argument "value" (default has type "None", argument has type "Union[int, str]")
    ...


def bar(value: Union[int, str] = None) -> None: # no error
    ...

https://mypy-play.net/?mypy=latest&python=3.10&gist=13ab271a59d6301d98dac48ccb87e9c8

@DetachHead DetachHead added the bug mypy got something wrong label Aug 17, 2021
@Zymergen-jvandezande
Copy link

I asked the same question on stackoverflow a little while back (and neglected to issue a bug report until today). PEP 484 indicates that the second example is the correct way to write it, as Optional should be explicit.

@erictraut
Copy link

Implicit optional is supported for backward compatibility, but its use is deprecated as per PEP 484, which states:

This is no longer the recommended behavior. Type checkers should move towards requiring the optional type to be made explicit.

Since the | union syntax is new, there is no backward-compatibility issue with enforcing the explicit use of None. I suspect that it was therefore intentional not to support the old implicit optional behavior with the new syntax.

You can avoid the error by explicitly including None in the union:

def foo(value: int | str | None = None) -> None:
    ...

@JelleZijlstra
Copy link
Member

I'm not sure this is really intentional, but I agree with @erictraut that we should keep the behavior as is. Implicit optional is a deprecated behavior that we're phasing out; we shouldn't introduce it with new syntax.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

4 participants