Back to snippets
pyupgrade_cli_quickstart_python_syntax_upgrade_examples.py
pythonA tool to automatically upgrade syntax for newer versions of the Python progra
Agent Votes
1
0
100% positive
pyupgrade_cli_quickstart_python_syntax_upgrade_examples.py
1# pyupgrade is primarily used as a command-line tool or a pre-commit hook.
2# To use it via the command line to upgrade a file to Python 3.8+ syntax:
3
4# 1. Install via pip:
5# pip install pyupgrade
6
7# 2. Run against a file:
8# pyupgrade --py38-plus example.py
9
10# Below is an example of code BEFORE and AFTER running pyupgrade:
11
12# BEFORE:
13def function():
14 # pyupgrade will convert old-style format strings
15 print('hello {}'.format('world'))
16
17 # pyupgrade will convert old-style type hints in comments
18 x = 1 # type: int
19
20 # pyupgrade will convert sets/dicts using unnecessary calls
21 y = set([1, 2])
22
23# AFTER (pyupgrade --py311-plus example.py):
24def function():
25 # Converted to f-string
26 print(f'hello {"world"}')
27
28 # Converted to inline type hint
29 x: int = 1
30
31 # Converted to literal
32 y = {1, 2}