Skip to content

os-path-expanduser (PTH111) should be marked unsafe #20214

@dscorbett

Description

@dscorbett

Summary

The fix for os-path-expanduser (PTH111) should be marked unsafe because the replacement is not always equivalent. If os.path.expanduser can’t determine a home directory, it returns the input unchanged, whereas pathlib.Path.expanduser raises an error. One reason it might not be able to determine a home directory is if the indicated user does not exist, but that is not the only possible reason. Example:

$ cat >pth111.py <<'# EOF'
import os
try: print(os.path.expanduser("~pth111_nonexistent_user"))
except RuntimeError as e: print(e)
# EOF

$ python pth111.py
~pth111_nonexistent_user

$ ruff --isolated check pth111.py --select PTH111 --preview --fix
Found 1 error (1 fixed, 0 remaining).

$ cat pth111.py
import os
import pathlib
try: print(pathlib.Path("~pth111_nonexistent_user").expanduser())
except RuntimeError as e: print(e)

$ python pth111.py
Could not determine home directory.

Version

ruff 0.12.11 (c2bc15b 2025-08-28)

Metadata

Metadata

Assignees

No one assigned

    Labels

    fixesRelated to suggested fixes for violationspreviewRelated to preview mode features

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions