Skip to content

PEP 604 union type alias not supported inside isinstance checks #16358

@michaeloliverx

Description

@michaeloliverx

Bug Report

PEP 604 introduced union type syntax X | Y which included support for the new syntax within calls to isinstance and issubclass.

mypy complains about code which runs correctly at runtime.

To Reproduce

class ANDNode:
    pass


class ORNode:
    pass


class NOTNode:
    pass


NodeType = ANDNode | ORNode | NOTNode

# mypy error
isinstance(NOTNode(), NodeType)

# okay
isinstance(NOTNode(), ANDNode | ORNode | NOTNode)

Gist URL: https://gist.github.com/mypy-play/4be2e08fa1da185af6e821705ea85744
Playground URL: https://mypy-play.net/?mypy=latest&python=3.11&gist=4be2e08fa1da185af6e821705ea85744

Expected Behavior

I would expect mypy to support a union type alias within an isinstance call to avoid duplication.

Actual Behavior

pep-604.py:16: error: Parameterized generics cannot be used with class or instance checks  [misc]
pep-604.py:16: error: Argument 2 to "isinstance" has incompatible type "<typing special form>"; expected "_ClassInfo"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.6.1 (compiled: yes)
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.11.0

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