Skip to content

mypy interprets arguments which contains a pipe to Literal as type strings instead of literals #16367

Closed
@InSyncWithFoo

Description

@InSyncWithFoo

Playground:

from typing import Literal


def f(v: Literal['foo', 'bar', 'foo|bar']) -> None:
    ...

Expected behavior:

f('foo')        # Pass
f('bar')        # Pass
f('foo|bar')    # Pass
f('baz')        # Fail
f('foo|')       # Fail
f('|qux')       # Fail
f('foo|qux')    # Fail

Actual behaviour:

def f(v: Literal['foo', 'bar', 'foo|bar']) -> None:  # error: Name "foo" is not defined  [name-defined]
  ...

Environment:

  • Mypy version used: 1.4/1.5/1.6/master branch.
  • Mypy command-line flags: None.
  • Mypy configuration options from mypy.ini (and other config files): None.
  • Python version used: 3.8/3.9/3.10/3.11/3.12.

This bug is found by StackOverflow user Håkon T. at this question.

It seems that mypy would try to interpret any string containing a pipe (|) as a type, and in this case it failed.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions