Skip to content

Support for detecting the flavour of pathlib subclasses #100502

Closed
@barneygale

Description

@barneygale

Feature or enhancement

Provide a way of checking whether a user subclass of pathlib.PurePath and Path uses POSIX or Windows semantics

The Problem

Now that #68320 is resolved, users can subclass pathlib.PurePath and Path directly:

import pathlib

class MyPath(pathlib.Path):
    pass

path = MyPath('foo')

However, there's no (public) procedure to detect whether an instance of MyPath uses POSIX or Windows semantics.

A non-public way of doing it:

path._flavour is posixpath  # Check whether the path object uses POSIX semantics
path._flavour is ntpath  # Check whether the path uses Windows semantics
path._flavour is os.path  # Check whether the path uses the current OS's semantics

Note that checking isinstance(path, PurePosixPath) (etc) won't work, as user subclasses of PurePath and Path do not have the POSIX- and Windows-specific subclasses in their class hierarchy.

The Proposal

Make the _flavour attribute public; document it. Possible names:

  • flavour (simply remove the underscore)
  • pathmod (used internally in older pathlib versions)
  • module (used in the longstanding thirdparty path package)

Alternatives

We could make the PurePosixPath and PureWindowsPath classes 'protocols', which support isinstance() checks even when the passed object isn't a conventional subclass. But:

  1. The implementation will be more complex
  2. It could open a can of worms about whether PurePosixPath and PureWindowsPath should be proper protocols, and not directly instantiable.

A further alternative would be to add an is_posix() method, which gels pretty nicely with the existing is_*() and as_posix() methods.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions