flake8-use-pathlib
flake8-use-pathlib is a plugin for the Flake8 linter that identifies patterns in Python code where functions from the `os.path` module (and other `os` functions) can be replaced by a more modern, object-oriented approach using the `pathlib` module. It helps developers write cleaner, more consistent, and cross-platform compatible code for file system operations. The current version is 0.3.0, released in August 2022, and it is actively maintained, with its rules also integrated into linters like Ruff.
Warnings
- breaking The package was previously named `flake8-pathlib`. Users should ensure they are installing `flake8-use-pathlib` as the former name is deprecated and no longer updated.
- gotcha While `pathlib` generally improves code, converting `Path` objects to `str` too early, e.g., `open(str(my_path))`, negates `pathlib`'s benefits. Python's `open()` (since 3.6) and most modern libraries natively accept `Path` objects.
- gotcha Some autofixes derived from `flake8-use-pathlib` rules (e.g., for `os.path.expanduser` to `Path.expanduser`) are considered 'unsafe' because `os.path` and `pathlib.Path` methods can have subtly different behaviors (e.g., error handling) or return types.
- gotcha Using `pathlib` can sometimes be less performant than lower-level `os` module alternatives, especially on older Python versions or in performance-critical sections of code.
- gotcha Flake8's configuration file discovery changed in version 5.0.0. Configuration in `~/.flake8` is explicitly ignored for global settings.
Install
-
pip install flake8-use-pathlib
Quickstart
# 1. Install flake8-use-pathlib (if you haven't already)
# pip install flake8 flake8-use-pathlib
# 2. Create a Python file, e.g., my_app.py, with some os.path usage:
# import os
#
# def get_absolute_path(filename):
# return os.path.abspath(filename)
#
# def list_directory(path):
# return os.listdir(path)
#
# print(get_absolute_path('file.txt'))
# print(list_directory('.'))
# 3. Run flake8 from your terminal in the directory containing my_app.py:
# flake8 my_app.py
# Expected output (or similar, depending on flake8 version and other plugins):
# my_app.py:4:12: PL100 os.path.abspath("filename") should be replaced by filename_path.resolve() (os-path-abspath)
# my_app.py:7:12: PL208 os.listdir(path) should be replaced by path_obj.iterdir() (os-listdir)