Modernize Your Python Code Automatically with pyupgrade

Outdated syntax accumulates over time, creating technical debt. However, manually updating syntax across large codebases is extremely time-consuming and is prone to mistakes.

pyupgrade automates this process by scanning your code and applying modern syntax upgrades. It’s designed to work as both a standalone tool and a pre-commit hook, making it easy to integrate into your development workflow.

Let’s look at some before-and-after examples to see how pyupgrade can improve your code:

Simplifying Set Creation

# Before
set([1, 2])
# After
{1, 2}

pyupgrade replaces the old set() constructor with a more concise set literal.

Set Comprehensions

# Before
set([x for x in y])
# After
{x for x in y}

It converts list comprehensions inside set() to set comprehensions.

Dictionary Comprehensions

# Before
dict([(a, b) for a, b in y])
# After
{a: b for a, b in y}

List comprehensions creating key-value pairs are converted to dictionary comprehensions.

f-strings

# Before
'%s %s' % (a, b)
# After
f'{a} {b}'

Old-style string formatting is updated to use modern f-strings.

Equality Comparisons

# Before
x is 5
# After
x == 5

Incorrect identity comparisons with literals are fixed to use equality.

Unnecessary Conversions

# Before
str("foo")
# After
"foo"

Redundant string conversions are removed.

Class Definitions

# Before
class C(object): pass
# After
class C: pass

Explicit inheritance from object is removed in Python 3.

Generator Expressions

# Before
foo, bar, baz = [fn(x) for x in items]
# After
foo, bar, baz = (fn(x) for x in items)

List comprehensions used in unpacking are converted to generator expressions for better memory efficiency.

Type Hinting

# Before
def f() -> Optional[str]:
# After
def f() -> str | None:

Type hints are updated to use the new union syntax introduced in Python 3.10.

Link to pyupgrade.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top