Editor

Refactor Into a Package Registry

Advanced · Refactor · from How to Create and Structure a Python Package

From the lesson: How to Create and Structure a Python Package

Imagine you have a filing cabinet. Right now, all your papers are thrown in one big drawer - recipes mixed with homework mixed with tax forms. Finding anything is a nightmare.

Read the lesson

The code below uses separate variables to track modules in a package. Refactor it into a single class called PackageRegistry with:

  • An __init__ method that sets the package name and an empty dictionary modules
  • A register(module_name, description) method that adds to modules
  • A get_info() method that returns a formatted string showing the package name and each module on its own line in the format - module_name: description
  • The output must match exactly.

    # Messy code: refactor this into a PackageRegistry class
    pkg_name = 'analytics'
    pkg_modules = {}
    pkg_modules['stats'] = 'Statistical functions'
    pkg_modules['charts'] = 'Chart generation'
    pkg_modules['export'] = 'Data export tools'
    info = f'Package: {pkg_name}'
    for mod, desc in pkg_modules.items():
    info += f'\n - {mod}: {desc}'
    print(info)

    What Check runs

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

    RunsExpected output
    pkg = PackageRegistry('analytics') pkg.register('stats', 'Statistical functions') pkg.register('charts', 'Chart generation') pkg.register('export', 'Data export tools') print(pkg.get_info())Package: analytics - stats: Statistical functions - charts: Chart generation - export: Data export tools
    pkg = PackageRegistry('web') pkg.register('routes', 'URL routing') print(pkg.get_info())Package: web - routes: URL routing

    More Package exercises

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