Repository navigation
pathlib ABCs: add protocols for supporting types #127456
Copy link
Copy link
Closed
Labels
stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytopic-pathlibtype-featureA feature request or enhancementA feature request or enhancement
Description
Activity
- addedtype-featureA feature request or enhancementA feature request or enhancement
on Nov 30, 2024 Penny for your thoughts on this @encukou :)
If you want to avoid adding a dependency on the typing module at runtime, you can use a similar technique to what we do with the protocol-like ABCs in
collections.abc,contextlibandos:- Use ABCs for the runtime implementation
- But add them to this allowlist in
typingso that the typing module treats them the same way it does protocol classes:Lines 1940 to 1948 in 328187c
_PROTO_ALLOWLIST = { 'collections.abc': [ 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator', 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer', ], 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'], 'os': ['PathLike'], } - And in typeshed, pretend that they're protocols so that type checkers treat them identically to "actual" protocols
Reacted by Barney GaleThanks Alex - that will be useful when/if when make
PathBaseand friends public, but for now I might makepathlib._typesan "orphan" module that's imported by nothing else. This also lets me add type annotations for free. It's a bit similar towsgiref.types. Do you think I'm missing a pitfall with that approach?Oh, if that's the plan then that should be fine, yup!
- addedstdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directory
on Dec 7, 2024
Metadata
Metadata
Assignees
Labels
stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytopic-pathlibtype-featureA feature request or enhancementA feature request or enhancement
Feature or enhancement
For typing and documentation purposes, it would be useful to define three protocols in pathlib:
Parser: likeos.path, but including only pure functionality that's essential forPurePathBaseDirEntry: likeos.DirEntry, but without some non-portable methods (likeinode())StatResult: likeos.stat_result, but without the tuple-like interface, and dropping non-essential attributesThese could be defined in a private module like
pathlib._types. For performance reasons that module shouldn't be imported by any other pathlib module.If/when we make
PathBasepublic, we'll also make these protocols public.See also: https://discuss.python.org/t/make-pathlib-extensible/3428/196
Linked PRs
Parser.sep#127725