pytest icon indicating copy to clipboard operation
pytest copied to clipboard

Replaced `typing.Self` with `typing_extensions.Self`

Open Avasam opened this issue 1 year ago • 0 comments

Fixes https://github.com/pytest-dev/pytest/pull/11916#issuecomment-2313758038

Importing Self from typing breaks the return type on Python 3.9 and under. You should be using from typing_extension import Self instead.

For example, the following code:

def pytest_collect_file(file_path: pathlib.Path, parent: Node) -> CheckdocsItem | None:
    if file_path.name not in project_files:
        return None
    return CheckdocsItem.from_parent(parent, name='project')

Will error with Returning Any from function declared to return "CheckdocsItem | None" [no-any-return] on 3.8 & 3.9, but pass on 3.10+ Which can only be worked around by disabling the error entirely in mypy, or doing:

def pytest_collect_file(file_path: pathlib.Path, parent: Node) -> CheckdocsItem | None:
    if file_path.name not in project_files:
        return None
    if sys.version_info >= (3, 10):
        return CheckdocsItem.from_parent(parent, name='project')
    else:
        return cast(CheckdocsItem, CheckdocsItem.from_parent(parent, name='project'))

Avasam avatar Aug 27 '24 23:08 Avasam