Skip to content

Mypy doesn't recognize None is checked when using or operator #13725

@GlenNicholls

Description

@GlenNicholls

Bug Report

When I use or to handle None, mypy doesn't recognize that the code handles the None case and issues errors about accessing attributes:

from typing import Optional

def func(arg: Optional[list] = None) -> list:
  arg = arg or []
  return arg.append(1)

I get a union-attr error for append. To fix this, I can do the following:

if arg is None:
  arg = []

However, I think this is wrong because the code is equivilent. Am I'm missing something here?

Expected Behavior

I would expect that when using arg or [], mypy would recognize that arg is never None after that line (assuming I don't override).

Actual Behavior

error: Item "None" of "Optional[list]" has no attribute "append" [union-attr]

Your Environment

  • Mypy version used: 0.971
  • Mypy configuration options from pyproject.toml:
    [tool.mypy]
    warn_unused_configs = true
    warn_unused_ignores = true
    install_types = true
    non_interactive = true
    check_untyped_defs = true
    show_error_codes = true
    show_error_context = true
    pretty = true
    color_output = true
  • Python version used: 3.9
  • Operating system and version: Ubuntu 20.04

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions