Skip to content

Make PurePath initializer args available as an attribute #131916

Open
@barneygale

Description

@barneygale

Feature or enhancement

Proposal:

I propose that we add a pathlib.PurePath.segments attribute that stores the original arguments given to the PurePath initializer. If we did this, then:

  1. Users would be able to implement their own joinpath() / __truediv__()-like methods without resorting to PurePath.parts (requires normalization - slow!) or the private PurePath._raw_paths attribute.
  2. In the pathlib ABCs, we can make JoinablePath.segments abstract, and use it from a default implementation of JoinablePath.__str__().
    • N.B. JoinablePath.__str__() is currently abstract, which is weird given it's non-abstract in object.

Usage would look like:

>>> p = PurePath('/usr', 'bin/python3')
>>> p.segments
('/usr', 'bin/python3')

When a PurePath object is given as an argument, its segments should be merged:

>>> p = PurePath('/usr', PurePath('bin', 'python3'))
>>> p.segments
('/usr', 'bin', 'python3')

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

https://discuss.python.org/t/protocol-for-virtual-filesystem-paths/82753/8

Linked PRs

Activity

added a commit that references this issue on Mar 30, 2025

pythonGH-131916: Add `pathlib.PurePath.segments`

encukou

encukou commented on Apr 29, 2025

@encukou
Member

Hi! Sorry for the delay.

Thinking about it more, I'm not comfortable with exposing non-normalized segments.
It would allow access to superficial details that pathlib currently hides, with unexpected consequences. In particular, I think people would (ab)use it to distinguish between paths with and without a trailing slash.

>>> PurePath('/usr/').segments
('/usr/',)
>>> PurePath('/usr').segments
('/usr',)
>>> PurePath('/usr/') == PurePath('/usr')
True

With that, using parts for unknown path types seems safer. For performance you'd need to use type-specific internals.

Similarly, I think a default __str__ should look at normalized data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @encukou@barneygale@picnixz

        Issue actions

          Make `PurePath` initializer args available as an attribute · Issue #131916 · python/cpython