Editor

Refactor the Version Bumper

Intermediate · Refactor · from How to Package and Publish Your Python Code to PyPI

From the lesson: How to Package and Publish Your Python Code to PyPI

Imagine you've written a fantastic recipe. Right now it only lives in your kitchen notebook. To share it with the world, you'd need to format it nicely, package it into a cookbook, and get it onto bookstore shelves.

Read the lesson

The code below bumps version numbers using repetitive if/elif blocks. Refactor it into a clean function called bump_version(version, part) where part is 'major', 'minor', or 'patch'. The function should return the new version string. When bumping major, reset minor and patch to 0. When bumping minor, reset patch to 0.

# Messy version bumping code - refactor this!
version = '1.2.3'
parts = version.split('.')
major = int(parts[0])
minor = int(parts[1])
patch = int(parts[2])
# Bump major
new_major = f'{major + 1}.0.0'
print(f'Major bump: {new_major}')
# Bump minor
new_minor = f'{major}.{minor + 1}.0'
print(f'Minor bump: {new_minor}')
# Bump patch
new_patch = f'{major}.{minor}.{patch + 1}'
print(f'Patch bump: {new_patch}')

What Check runs

Your code runs first, then each of these lines. The output must match exactly.

RunsExpected output
print(bump_version('1.2.3', 'major')) print(bump_version('1.2.3', 'minor')) print(bump_version('1.2.3', 'patch'))2.0.0 1.3.0 1.2.4
print(bump_version('0.9.9', 'minor')) print(bump_version('0.9.9', 'patch'))0.10.0 0.9.10

More PyPI Packaging exercises

All Python exercises · 50 practice problems · Modules & Packaging quiz