A tool and pre-commit hook to automatically upgrade Python syntax for newer versions of the language.
—
Command-line tool for upgrading Python files with extensive configuration options for different Python versions and preservation settings.
Main command-line interface function that processes files and applies transformations.
def main(argv: Sequence[str] | None = None) -> int:
"""
Main entry point for command-line interface.
Args:
argv: Command line arguments (None uses sys.argv)
Returns:
Exit code:
- 0: Success (no changes or --exit-zero-even-if-changed used)
- 1: Files were modified or errors occurred
"""# Default (Python 3+)
pyupgrade file.py
# Base version targets
pyupgrade --py3-plus file.py # Python 3+ upgrades (alias: --py3-only)
pyupgrade --py3-only file.py # Same as --py3-plus
# Specific version targets
pyupgrade --py36-plus file.py
pyupgrade --py37-plus file.py
pyupgrade --py38-plus file.py
pyupgrade --py39-plus file.py
pyupgrade --py310-plus file.py
pyupgrade --py311-plus file.py
pyupgrade --py312-plus file.py
pyupgrade --py313-plus file.py
pyupgrade --py314-plus file.py# Keep percent-style format strings
pyupgrade --keep-percent-format file.py
# Keep mock imports (don't replace with unittest.mock)
pyupgrade --keep-mock file.py
# Keep runtime typing imports
pyupgrade --keep-runtime-typing file.py
# Exit with code 0 even if files were changed
pyupgrade --exit-zero-even-if-changed file.py# Basic usage - upgrade single file
pyupgrade example.py
# Upgrade multiple files
pyupgrade src/*.py tests/*.py
# Upgrade for Python 3.10+ with format preservation
pyupgrade --py310-plus --keep-percent-format src/*.py
# Use with pre-commit (exit 0 on changes)
pyupgrade --exit-zero-even-if-changed --py39-plus *.py
# Process stdin
cat example.py | pyupgrade -.pre-commit-config.yaml:
repos:
- repo: https://github.com/asottile/pyupgrade
rev: v3.20.0
hooks:
- id: pyupgrade
args: [--py310-plus]import subprocess
import sys
def upgrade_codebase():
"""Upgrade entire codebase to Python 3.11+."""
result = subprocess.run([
'pyupgrade',
'--py311-plus',
'--keep-percent-format',
*sys.argv[1:] # Pass through file arguments
])
return result.returncode
if __name__ == '__main__':
sys.exit(upgrade_codebase())Install with Tessl CLI
npx tessl i tessl/pypi-pyupgrade