Skip to content

Getting a union from an and expression #16565

Open
@Dreamsorcerer

Description

@Dreamsorcerer

Bug Report

I'd hope there's already an issue for this, but couldn't find one.
When using and, mypy infers a union from both sides when the truthy evaluation makes it impossible.

Actual code trigerring the error: https://github.com/aio-libs/aiohttp/pull/7879/files#diff-720910fd022b9ba8b7ddf0cb446ce5e1afe443f4287ad26a1eb4dc4b5b5f4508R944

To Reproduce

class Protocol:
    upgraded: bool

class Connection:
    protocol: Protocol | None

conn: Connection | None
protocol = conn and conn.protocol
assert protocol is not None
protocol.upgraded  # error: Item "Connection" of "Connection | Protocol" has no attribute "upgraded"  [union-attr]

Expected Behavior

protocol can't be Connection, so this error shouldn't happen.

Your Environment

  • Mypy version used: 1.7.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions