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

typing.Optional with not None default, should not type check None value until it mutate. #10743

Closed
sileht opened this issue Jun 30, 2021 · 1 comment
Labels
bug mypy got something wrong

Comments

@sileht
Copy link
Contributor

sileht commented Jun 30, 2021

The example is self explicit.
It looks weird that we need to check for final_params is None when we just set it explicitly to something else.

import typing

def local_optional_default_not_working(
  params: typing.Optional[typing.Dict[str, str]] = None,
) -> None:
    final_params: typing.Optional[typing.Dict[str, str]] = {"per_page": "100"}
    if params is not None:
        final_params.update(params)


def local_optional_default_workaround1(
  params: typing.Optional[typing.Dict[str, str]] = None,
) -> None:
    final_params: typing.Optional[typing.Dict[str, str]]
    final_params = {"per_page": "100"}

    if params is not None:
        final_params.update(params)

def local_optional_default_workaround2(
  params: typing.Optional[typing.Dict[str, str]] = None,
) -> None:
    final_params: typing.Optional[typing.Dict[str, str]] = {"per_page": "100"}
    if final_params is None:
        raise RuntimeError("final_params can be None really ?")

    if params is not None:
        final_params.update(params)

Expected Behavior

No mypy error

Actual Behavior

$ mypy --strict optional_local_default.py
optional_local_default.py:8: error: Item "None" of "Optional[Dict[str, str]]" has no attribute "update"
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.910
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files): strict
  • Python version used: 3.9
  • Operating system and version: arch
@sileht sileht added the bug mypy got something wrong label Jun 30, 2021
@hauntsaninja
Copy link
Collaborator

Duplicate of #2008 (also see the typing-sig thread linked at the end)

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

2 participants