Skip to content

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

Closed

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.

Activity

  1. henryiii commented on Apr 21, 2024

    @henryiii
    Contributor

    Same issue with Literal["uv", "pip", "uv|pip"] producing a name error on uv not being defined.

  2. added a commit that references this issue on Apr 22, 2024
    1072c78
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions