Pyupgrade is a tool that automatically upgrades your Python syntax to newer versions, helping you take advantage of modern Python features.
Pyupgrade scans your Python code for outdated syntax patterns and upgrades them to use newer Python features. It helps:
- Modernize your codebase
- Improve code readability
- Take advantage of performance improvements in newer Python syntax
- Maintain compatibility with specified Python versions
Pyupgrade is included as a development dependency:
# Install with other development dependencies
uv sync --devTo install it directly:
uv pip install pyupgradeIn this project, Pyupgrade is used to:
- Automatically upgrade Python syntax to Python 3.11+
- Maintain modern Python syntax across the codebase
- Run as part of the pre-commit hooks and CI/CD pipeline
Pyupgrade is configured as a poethepoet task:
[tool.poe.tasks]
pyupgrade = "pyupgrade --py311-plus"This configuration specifies that the code should be upgraded to use Python 3.11+ syntax.
To run Pyupgrade on the project:
# Run via poethepoet
uv run poe pyupgrade
# Run directly
uv run pyupgrade --py311-plus src/**/*.py# Specify Python version
uv run pyupgrade --py39-plus src/**/*.py
# Keep specific syntax unchanged
uv run pyupgrade --keep-percent-format src/**/*.py
# Run on specific files
uv run pyupgrade path/to/file.pyBefore:
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
combined = dict(list(dict1.items()) + list(dict2.items()))After:
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
combined = {**dict1, **dict2}Before:
name = "World"
greeting = "Hello, {}!".format(name)After:
name = "World"
greeting = f"Hello, {name}!"Before:
from typing import List, Dict, Optional
names: List[str] = ["Alice", "Bob"]
ages: Dict[str, int] = {"Alice": 30, "Bob": 25}
maybe_name: Optional[str] = NoneAfter:
names: list[str] = ["Alice", "Bob"]
ages: dict[str, int] = {"Alice": 30, "Bob": 25}
maybe_name: str | None = None- Run Pyupgrade regularly: Include Pyupgrade in your pre-commit hooks to ensure consistent syntax.
- Specify the correct Python version: Use the appropriate
--pyXX-plusflag for your project's minimum Python version. - Combine with other tools: Use Pyupgrade alongside tools like Ruff and Flynt for comprehensive code modernization.
- Review changes: Some syntax upgrades might change behavior in subtle ways, so review changes carefully.