You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
note: Revealed type is "Union[Literal[1], None]"
Success: no issues found in 1 source file
For the runtime counterpart, this will result in a TypeError: unsupported operand type(s) for |: 'int' and 'NoneType' if the module doesn't have from __future__ import annotations or invalid results for runtime annotation inspectors (e.g. in the case of typing.Literal[1 | 2]).
Expected Behavior
Maybe:
error: Invalid type: Literal[...] cannot contain arbitrary expressions [valid-type]
note: Revealed type is "Any"
Your Environment
Mypy version used: 1.10
Mypy command-line flags: None
Mypy configuration options from mypy.ini (and other config files): None
My understanding is that Literal[...] inside a union is valid, such as Union[Literal[1], None]. Also, Literal[1, None] is valid and equivalent to Literal[1] | None.
However, a union expression inside Literal[...] should not be valid, e.g. Literal[1 | None] or Literal[Union[Literal[1], None]](please correct me if I am wrong, cc @hauntsaninja ).
The main open question is aliases:
Alias1 = Literal[1, None]
x: Literal[Alias1] # valid? since it's a nested Literal
Alias2 = Literal[1] | None
y: Literal[Alias2] # valid, or should this also be rejected?
Alias1 current is handled by the mypy via the existing UnionType flattening logic in analyze_literal_param:
Alias1 = Literal[1, None]
x: Literal[Alias1] # valid? since it's a nested Literal
Alias2 = Literal[1] | None
y: Literal[Alias2] # valid, or should this also be rejected?
Activity
TypeError: unsupported operand type(s) for |: 'str' and 'str'#18827 as a duplicate of this issue97littleleaf11 commentedon May 24, 2026
My understanding is that
Literal[...]inside a union is valid, such asUnion[Literal[1], None]. Also,Literal[1, None]is valid and equivalent toLiteral[1] | None.However, a union expression inside Literal[...] should not be valid, e.g.
Literal[1 | None]orLiteral[Union[Literal[1], None]](please correct me if I am wrong, cc @hauntsaninja ).The main open question is aliases:
Alias1 current is handled by the mypy via the existing UnionType flattening logic in analyze_literal_param:
hauntsaninja commentedon May 25, 2026
Yeah, it makes sense to disallow this, at least because runtime typing will not work well.
Note you might want to also add a test in the conformance test suite for this https://github.com/python/typing
bzoracler commentedon May 25, 2026
@97littleleaf11 The typing specs say those are valid: