python / python/cpython

Suffix in pathlib is not behaving like a file extension

Open
#121,347 13 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

OS-windows topic-pathlib type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

According to the docs here a suffix is defined as:

The file extension of the final component, if any

But pathlib doesn't behave as expected, illustrating that on Python 3.12.4:

>>> Path("Mr. Smith resume for review").suffix
'. Smith resume for review'

This is particularly problematic for methods like with_suffix. According to the docs here that should:

Return a new path with the suffix changed. If the original path doesn’t have a suffix, the new suffix is appended instead. If the suffix is an empty string, the original suffix is removed

But as established above, that results in:

>>> Path("Mr. Smith resume for review").with_suffix(".pdf")
PosixPath('Mr.pdf')

I've characterized that as a bug as that is not working as described, but could also be a matter of documentation improvement.

I see a few ways:

  1. Implement add_suffix, or an argument to with_suffix, but I know that has been discussed before and was ultimately decided against. Also this is a matter of how suffix is defined, not how it's processed.
  2. Sanity check what a suffix can be, e.g. suffix can't have white space. But ultimately difficult without making assumption.
  3. Adjust the documentation: Clarify that suffix is not equal to file extension but something like last segment separated by a dot or similar. Maybe even with a warning that this can have unexpected behavior as showcased above.
CPython versions tested on:

3.12

Operating systems tested on:

Linux, Windows

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the Python 3.12 pathlib examples for PurePath.suffix and with_suffix, then inspect the pathlib implementation and documentation for how suffixes are defined. Compare the observed behavior with the documented file-extension wording and determine whether the issue is resolved by behavior changes or documentation clarification.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
operating-systems
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.