Using a pipe symbol in typing.Literal string

Question:

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.

Asked By: Håkon T.

||

Answers:

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

Answered By: InSync
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.