-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Description
Summary
The fixes for os-rename (PTH104), os-replace (PTH105), os-getcwd (PTH109), and os-readlink (PTH115) should generally be marked unsafe because the replacements have different return types. Example:
$ cat >pth1.py <<'# EOF'
import os
import sys
# code name original return type -> replacement
# PTH104 os-rename None -> Path
print(os.rename("pth1.py", "pth1.py.bak"))
# PTH105 os-replace None -> Path
print(os.replace("pth1.py.bak", "pth1.py"))
# PTH109 os-getcwd str -> Path
# os-getcwdb bytes -> Path
try: print(os.getcwd().upper())
except AttributeError as e: print(e)
try: print(os.getcwdb().upper())
except AttributeError as e: print(e)
# PTH115 os-readlink str -> Path
try: print(os.readlink(sys.executable).upper())
except AttributeError as e: print(e)
# EOF
$ ruff --isolated check pth1.py --select PTH --preview --unsafe-fixes --fix
Found 5 errors (5 fixed, 0 remaining).
$ python pth1.py
pth1.py.bak
pth1.py
'PosixPath' object has no attribute 'upper'
'PosixPath' object has no attribute 'upper'
'PosixPath' object has no attribute 'upper'The fixes are still safe in two cases. When the function call is the top-level expression in its statement, the return value is not used, so the return type does not matter, so the fix is safe. This case is common enough and easy enough to detect that I think it is worth supporting. When the original function returns a str or bytes and the replacement returns a Path and the function call is an argument to a function that interprets that argument as a path-like object and whose return value doesn’t expose the difference, then the difference in return type doesn’t matter, so the fix is safe. This case is harder to support because it requires reviewing each such function carefully, but if the ecosystem report reveals a common function that could be safe, it might be worth supporting it.
This all applies to os-path-abspath (PTH100), os-path-expanduser (PTH111), and os-path-dirname (PTH120) too. Their fixes are already marked unsafe, but their documentation should explain this additional reason for unsafety.
Version
ruff 0.14.4 (c7ff982 2025-11-06)