|
| 1 | +from __future__ import annotations |
| 2 | +from _typeshed import StrOrBytesPath |
| 3 | +from os import PathLike |
| 4 | +from os.path import abspath, expanduser, expandvars |
| 5 | +from typing_extensions import assert_type |
| 6 | +from typing import AnyStr, Union |
| 7 | + |
| 8 | + |
| 9 | +def test_str_path(str_path: StrOrBytesPath) -> None: |
| 10 | + # These methods are currently overloaded to work around python/mypy#17952 & python/mypy#11880 |
| 11 | + # Let's ensure that they'll still work with a StrOrBytesPath if the workaround is removed |
| 12 | + |
| 13 | + assert_type(abspath(str_path), Union[str, bytes]) |
| 14 | + assert_type(expanduser(str_path), Union[str, bytes]) |
| 15 | + assert_type(expandvars(str_path), Union[str, bytes]) |
| 16 | + |
| 17 | + |
| 18 | +# See python/mypy#17952 |
| 19 | +class MyPathMissingGeneric(PathLike): # type: ignore # Explicitly testing w/ missing type argument |
| 20 | + def __init__(self, path: str | bytes) -> None: |
| 21 | + super().__init__() |
| 22 | + self.path = path |
| 23 | + |
| 24 | + def __fspath__(self) -> str | bytes: |
| 25 | + return self.path |
| 26 | + |
| 27 | + |
| 28 | +# MyPathMissingGeneric could also be fixed by users by adding the missing generic annotation |
| 29 | +class MyPathGeneric(PathLike[AnyStr]): |
| 30 | + def __init__(self, path: AnyStr) -> None: |
| 31 | + super().__init__() |
| 32 | + self.path: AnyStr = path |
| 33 | + |
| 34 | + def __fspath__(self) -> AnyStr: |
| 35 | + return self.path |
| 36 | + |
| 37 | + |
| 38 | +class MyPathStr(PathLike[str]): |
| 39 | + def __init__(self, path: str) -> None: |
| 40 | + super().__init__() |
| 41 | + self.path = path |
| 42 | + |
| 43 | + def __fspath__(self) -> str: |
| 44 | + return self.path |
| 45 | + |
| 46 | + |
| 47 | +abspath(MyPathMissingGeneric(".")) |
| 48 | +expanduser(MyPathMissingGeneric(".")) |
| 49 | +expandvars(MyPathMissingGeneric(".")) |
| 50 | + |
| 51 | +abspath(MyPathGeneric(".")) |
| 52 | +expanduser(MyPathGeneric(".")) |
| 53 | +expandvars(MyPathGeneric(".")) |
| 54 | + |
| 55 | +abspath(MyPathStr(".")) |
| 56 | +expanduser(MyPathStr(".")) |
| 57 | +expandvars(MyPathStr(".")) |
0 commit comments