Skip to content

APIs related to importlib.abc.PathEntryFinder should use protocol instead #11541

Closed
@abravalheri

Description

@abravalheri

Although importlib.abc.PathEntryFinder is defined as an abstract class in the standard library, path entry finders are intentionally loosely defined in the Python docs (and originated PEPs), so that the only thing that needs to be implemented is one method (find_spec). This matches the functioning of a protocol.

The reason why the abstract class is defined is probably informational (for documentation purposes) + extra code re-use internally in the stdlib. This situation is similar to importlib.abc.MetaPathFinder, and other importlib.abc classes (like loaders).

This affects

path_hooks: list[Callable[[str], PathEntryFinder]]
and probably other places.

For example, I would expect the following snippet to type check with no problems:

import sys
from types import ModuleType
from importlib.machinery import ModuleSpec
from typing_extensions import Self


class Finder:
    @classmethod
    def path_hook(cls, path_entry: str) -> type[Self]:
        return cls  # simplified mock for demonstration purposes only

    @classmethod
    def find_spec(cls, fullname: str, target: ModuleType | None = None)  -> ModuleSpec | None:
        return None  # simplified mock for demonstration purposes only
    
        
sys.path_hooks.append(Finder.path_hook)

But instead I am having an error:

main.py:9: error: Missing return statement  [empty-body]
main.py:17: error: Argument 1 to "append" of "list" has incompatible type "Callable[[str], type[Finder]]"; expected "Callable[[str], PathEntryFinder]"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

https://mypy-play.net/?mypy=latest&python=3.12&gist=dfd3a0dcf277afc43cf59c8eb07afc5b

Metadata

Metadata

Assignees

No one assigned

    Labels

    stubs: improvementImprove/refactor existing annotations, other stubs issues

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions