5

I have a function that accepts certain literals for a specific argument:

from typing import Literal

def fn(x: Literal["foo", "bar", "foo|bar"]) -> None:
    reveal_type(x)

The third contains a pipe symbol (|), "foo|bar". This is interpreted by mypy as an error, as the name foo is not defined.

I guess this happens due to how forward references are evaluated? I use Python 3.8 with:

from __future__ import annotations

Is there a way to make this work? I can not change the string due to breaking backward compatibility, but currently, the whole annotation is revealed as Any, i.e. it holds no value.

7
  • It would be helpful, too, if in your minimal reproducible example you showed the mypy usage you're using to demonstrate that "the whole annotation is revealed as Any" Commented Oct 29, 2023 at 21:02
  • 1
    As far as I can tell, this is a bug in mypy. Other type checkers (pyright, PyCharm inspections) can handle this without issue. I don't see an existing issue for it, so it would be worth reporting Commented Oct 29, 2023 at 21:20
  • 3
    Going by how, by design, Literal['Color.RED'] interprets 'Color.RED' as a string instead of a forward reference, I think mypy should be changed to interpret "foo|bar" as a string instead of a forward reference here too. Commented Oct 29, 2023 at 21:21
  • 3
    You should do that anyway. It’s a bug. Commented Oct 29, 2023 at 21:24
  • 1
    @HåkonT. I filed one: #16367. Commented Oct 29, 2023 at 21:31

1 Answer 1

2

This bug is now fixed. The change hasn't been released yet, however.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.