Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
abravalheri opened this issue Mar 8, 2024 · 0 comments · Fixed by #11890
Closed

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

abravalheri opened this issue Mar 8, 2024 · 0 comments · Fixed by #11890
Labels
stubs: improvement Improve/refactor existing annotations, other stubs issues

Comments

@abravalheri
Copy link
Contributor

abravalheri commented Mar 8, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stubs: improvement Improve/refactor existing annotations, other stubs issues
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants