reproducible code:
from pathlib import Path
from typing import overload
from typing_extensions import Literal, TypeAlias
StrPath: TypeAlias = str | Path
OpenModeA: TypeAlias = Literal["r", "w"]
OpenModeB: TypeAlias = Literal["r", "w", "x", "a"]
class Something:
@overload
def __init__(self, file: StrPath, mode: OpenModeA = "r") -> None: ...
@overload
def __init__(self, file: StrPath, mode: OpenModeB = "r") -> None: ...
def __init__(self, file: StrPath, mode: OpenModeA | OpenModeB = "r") -> None:
pass
file = "fileA.txt"
if file == "fileA.txt":
mode = "r"
elif file == "fileB.txt":
mode = "w"
else:
mode = "r"
Something(file=file, mode=mode) # mypy error: No overload variant of "Something" matches argument types "str", "str"Mypycall-overload
env:
❯ poetry env info
Virtualenv
Python: 3.11.8
Implementation: CPython
Path: .venv
Executable: .venv\Scripts\python.exe
Valid: True
mypy:
❯ poetry show mypy
name : mypy
version : 1.9.0
description : Optional static typing for Python
dependencies
- mypy-extensions >=1.0.0
- tomli >=1.1.0
- typing-extensions >=4.1.0