Modules, Packages and Namespaces · Practice
Quiz & exercises
Answer each question to see the explanation. Your best score is saved in this browser.
Quiz
Coding exercises
Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.
Exercise 1: Your own importer ✓ Passed
Write module_from_source(name, source) that mimics what import does with a module's source code:
1. If name is already in sys.modules, return the cached object (don't run any code). 2. Otherwise create a new module object named name. 3. Register it in sys.modules before running its code. 4. Execute source so that its global names end up in the module's namespace, and return the module.
Afterwards, a plain import <name> anywhere in the program should find your module.
import sys
import types
def module_from_source(name, source):
# your code here
pass
import sys, types, uuid
def _new_name():
return 'dyn_' + uuid.uuid4().hex[:8]
def test_namespace():
"""the source's names become module attributes"""
mod = module_from_source(_new_name(), 'x = 10\ndef double(n):\n return 2 * n\n')
assert isinstance(mod, types.ModuleType), f'expected a module, got {type(mod).__name__}'
assert mod.x == 10, f'x is {getattr(mod, "x", None)!r}'
assert mod.double(4) == 8
def test_module_name():
"""inside the module, __name__ is the module's name"""
name = _new_name()
mod = module_from_source(name, 'who = __name__\n')
assert mod.__name__ == name
assert mod.who == name, f'__name__ inside the module was {mod.who!r}'
def test_registered():
"""the module is cached and importable"""
name = _new_name()
mod = module_from_source(name, 'value = 1\n')
assert sys.modules.get(name) is mod, 'module not found in sys.modules'
ns = {}
exec(f'import {name} as imported', ns)
assert ns['imported'] is mod
def test_cache_hit():
"""a second call returns the cached module without running new code"""
name = _new_name()
first = module_from_source(name, 'x = 1\n')
second = module_from_source(name, 'x = 2\n')
assert second is first, 'a new module was created'
assert second.x == 1, 'the second source was executed'
def test_registered_before_running():
"""the module is in sys.modules while its code runs"""
name = _new_name()
mod = module_from_source(name, f'import sys\nseen = {name!r} in sys.modules\n')
assert mod.seen is True, 'module was not in sys.modules while its code ran'
Hints (3)
types.ModuleType(name)creates an empty module; its namespace ismod.__dict__.exec(code, namespace)runs code withnamespaceas its globals.- Put the module in
sys.modulesbefore callingexec, just as Python does.
Show a solution
import sys
import types
def module_from_source(name, source):
if name in sys.modules:
return sys.modules[name]
mod = types.ModuleType(name)
sys.modules[name] = mod
code = compile(source, filename=f'<{name}>', mode='exec')
exec(code, mod.__dict__)
return modExercise 2: What would a star-import bring in? ✓ Passed
Write public_names(module) that returns a sorted list of the names that from module import * would bind:
- if the module defines __all__, exactly the names it lists; - otherwise, every name in the module's namespace that doesn't start with an underscore.
def public_names(module):
# your code here
return sorted(vars(module))
import sys, types, uuid
def _make(source):
name = 'star_' + uuid.uuid4().hex[:8]
mod = types.ModuleType(name)
exec(source, mod.__dict__)
sys.modules[name] = mod
return mod
def _star(mod):
ns = {}
exec(f'from {mod.__name__} import *', ns)
return sorted(k for k in ns if k != '__builtins__')
def test_without_all():
"""without __all__, underscore names are skipped"""
mod = _make('a = 1\nb = 2\n_private = 3\ndef f(): pass\n')
assert public_names(mod) == ['a', 'b', 'f'], f'got {public_names(mod)}'
def test_with_all():
"""with __all__, exactly the listed names"""
mod = _make("__all__ = ['b', '_hidden']\na = 1\nb = 2\n_hidden = 3\n")
assert public_names(mod) == ['_hidden', 'b'], f'got {public_names(mod)}'
def test_matches_python():
"""agrees with a real star-import"""
for source in ['x = 1\n_y = 2\nimport math\n', "__all__ = ['x']\nx = 1\nz = 3\n"]:
mod = _make(source)
assert public_names(mod) == _star(mod), f'{public_names(mod)} != {_star(mod)}'
Hints (3)
vars(module)(ormodule.__dict__) is the module's namespace.- Use
getattr(module, '__all__', None)to check for__all__without an error. - Note that an imported module (like
mathafterimport math) is also a public name.
Show a solution
def public_names(module):
names = getattr(module, '__all__', None)
if names is not None:
return sorted(names)
return sorted(name for name in vars(module) if not name.startswith('_'))Exercise 3: A flat package interface ✓ Passed
A package contains two modules:
python product.py __all__ = ['Product'] (plus a private helper _slug) cart.py __all__ = ['Cart']
Write the source of the package's __init__.py in the string INIT_SOURCE so that users can write pkg.Product and pkg.Cart directly, the package's __all__ contains exactly Product and Cart, and private helpers are not exposed at package level.
The tests give the package a random name each time, so your __init__.py can't refer to the package by name.
INIT_SOURCE = ''' # your __init__.py code here '''
import importlib, sys, tempfile, uuid
from pathlib import Path
PRODUCT = "__all__ = ['Product']\n\nclass Product:\n def __init__(self, name, price):\n self.name, self.price = name, price\n\ndef _slug(text):\n return text.lower()\n"
CART = "__all__ = ['Cart']\n\nclass Cart:\n def __init__(self):\n self.items = []\n def add(self, product):\n self.items.append(product)\n def total(self):\n return sum(p.price for p in self.items)\n"
def _load():
root = Path(tempfile.mkdtemp())
name = 'shop_' + uuid.uuid4().hex[:8]
(root / name).mkdir()
(root / name / 'product.py').write_text(PRODUCT)
(root / name / 'cart.py').write_text(CART)
(root / name / '__init__.py').write_text(INIT_SOURCE)
sys.path.insert(0, str(root))
importlib.invalidate_caches()
try:
return importlib.import_module(name)
finally:
sys.path.remove(str(root))
def test_flat_access():
"""Product and Cart are available at package level"""
pkg = _load()
cart = pkg.Cart()
cart.add(pkg.Product('apple', 3))
cart.add(pkg.Product('pear', 4))
assert cart.total() == 7
def test_all():
"""the package's __all__ lists exactly Product and Cart"""
pkg = _load()
assert sorted(getattr(pkg, '__all__', [])) == ['Cart', 'Product'], f"__all__ is {getattr(pkg, '__all__', None)!r}"
def test_no_helpers():
"""private helpers stay inside their module"""
pkg = _load()
assert not hasattr(pkg, '_slug'), '_slug leaked into the package namespace'
Hints (3)
- Use relative imports such as
from .product import *; they don't depend on the package's name. - A star-import respects each module's
__all__, so_slugwon't come along. - After
from .product import *, the sub-module itself is available as the nameproductinside__init__.py, soproduct.__all__works.
Show a solution
INIT_SOURCE = '''
from .product import *
from .cart import *
__all__ = product.__all__ + cart.__all__
'''