Legends ofPythos
Claim your name
Writing Real Programs

Your own modules and packages

Lesson 14 of 16

Watch the lesson1:20 · with Sigrid
Every .py file is a module. Splitting one big script into several small files keeps each piece focused. You write the helper code in helpers.py, then pull it into your main program with an import statement.

Creating and importing modules

# write the module file
with open('helpers.py', 'w') as f:
    f.write("def greet(name):\n    return f'Hello, {name}!'\n")

# tell Python to forget its old search results
import importlib
importlib.invalidate_caches()

# now import it like any other module
from helpers import greet
Write a file from code, clear the cache, then import

The __name__ guard

When your program is the one being run directly, its name is '__main__'. When it is imported by another file, its name is just the filename without .py, for example helpers. That difference lets you write code that only runs when a module is executed on its own.
# inside helpers.py
def greet(name):
    return f'Hello, {name}!'

if __name__ == '__main__':
    print(greet('world'))  # runs only if you do: python helpers.py

Packages and inspection tools

A package is a folder that contains an __init__.py file (it can be empty). os.makedirs('shop', exist_ok=True) creates the folder, and then you import from inside it with a dot: from shop.pricing import total.
import os, importlib

os.makedirs('shop', exist_ok=True)
open('shop/__init__.py', 'w').close()          # an empty __init__.py
with open('shop/pricing.py', 'w') as f:
    f.write("def total(prices):\n    return sum(prices)\n")

importlib.invalidate_caches()
from shop.pricing import total
print(total([2, 3]))   # 5
A package with one module
To see what a module offers, dir(module) lists its names. Python looks for modules in the folders listed in sys.path, in order.

Your turn

0 of 3 solved

Exercise 1

+35 XP
Create a module from code. Write the text in SOURCE to a file named helpers.py using open() in write mode, call importlib.invalidate_caches(), then import helpers and store helpers.greet('Ada') in message. Finally, bring greet in directly with from helpers import greet as well.
import importlib


SOURCE = """def greet(name):
    return f'Hello, {name}!'
"""


# 1. write SOURCE to helpers.py
# 2. tell Python to look again for new modules
# 3. import helpers and store helpers.greet('Ada') in message
# 4. from helpers import greet

Run your code to check it against the tests.

Exercise 2

+35 XP
Write the source of a module yourself, as a string in SOURCE. The module defines area(w, h) returning w * h, prints f'loaded as {__name__}', and ends with an if __name__ == '__main__': block that prints 'running as a script'. Save it as shapes.py, invalidate the caches, import it, and store shapes.area(3, 4) in result. Because the module is imported, not run, the output shows loaded as shapes and nothing from the guarded block.
import importlib


SOURCE = """
"""  # write the module here


# save SOURCE as shapes.py, invalidate the caches, import shapes, then set result
result = None

Run your code to check it against the tests.

Exercise 3

+35 XP
Make a package. Create a folder kit with os.makedirs('kit', exist_ok=True), write VERSION = '1.0' into kit/__init__.py, and write a tools.py inside it that defines double(x) returning x * 2. Invalidate the caches, then import kit and from kit import tools, and store tools.double(21) in answer.
import importlib
import os


# 1. make the kit folder
# 2. write kit/__init__.py and kit/tools.py
# 3. invalidate the caches and import
answer = None

Run your code to check it against the tests.