How to configure ruff linter rules in pyproject.toml with Python

This Python script generates a pyproject.toml file with ruff linter rules, including selected and ignored rules, per-file ignores, and complexity limits.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 12 views 0 copies

Python code

26 lines
Python 3.9+
from pathlib import Path

def configure_ruff_rules(project_dir: str = "my_project") -> None:
    """Create a pyproject.toml with ruff linter rules for mock usage."""
    pyproject_path = Path(project_dir) / "pyproject.toml"
    pyproject_path.parent.mkdir(parents=True, exist_ok=True)

    config = """[tool.ruff]
line-length = 88

[tool.ruff.lint]
select = ["E", "W", "F", "I", "N", "S", "B", "A"]
ignore = ["S101"]

[tool.ruff.lint.per-file-ignores]
"tests/*" = ["S105", "S106"]

[tool.ruff.lint.mccabe]
max-complexity = 10
"""

    pyproject_path.write_text(config, encoding="utf-8")
    print(pyproject_path.read_text())

if __name__ == "__main__":
    configure_ruff_rules()

Output

stdout
[tool.ruff]
line-length = 88

[tool.ruff.lint]
select = ["E", "W", "F", "I", "N", "S", "B", "A"]
ignore = ["S101"]

[tool.ruff.lint.per-file-ignores]
"tests/*" = ["S105", "S106"]

[tool.ruff.lint.mccabe]
max-complexity = 10

How it works

The script uses pathlib.Path to construct the path to pyproject.toml and create the parent directory if it doesn't exist. It then writes a multi-line string containing the ruff configuration using write_text. The configuration selects common rule sets (E, W, F, I, N, S, B, A) and ignores S101 (assert usage) globally, with per-file ignores for tests. The mccabe section sets the maximum complexity to 10. Finally, it reads and prints the file to confirm the content was written correctly.

Common mistakes

  • Forgetting to create the parent directory, causing a FileNotFoundError when writing the file.
  • Using `open()` without specifying encoding, which may cause Unicode errors on some systems.
  • Misconfiguring the `select` and `ignore` keys, e.g., using `select = ["E", "W"]` instead of a single string list with proper syntax.
  • Overlooking that ruff uses `tool.ruff.lint` for lint settings, not `tool.ruff.lint` under a different section.

Variations

  1. Use `tomllib` to programmatically build the TOML structure instead of a string.
  2. Append or merge the ruff configuration into an existing pyproject.toml instead of overwriting it.

Real-world use cases

  • Bootstrapping a new Python project with consistent linting rules by generating pyproject.toml automatically.
  • Managing and templating ruff configurations across multiple microservices or repositories with a script to ensure uniformity.
  • Integrating ruff configuration generation into a CI/CD pipeline to enforce linting standards on every codebase.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Modern tooling

Related tutorials and quizzes for this topic.