Modules, Packages and Namespaces · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. Three different modules of your program each run import math. How many math module objects exist?
2. What does this print?
import sys, types

m = types.ModuleType('quiz_dyn')
m.x = 42
sys.modules['quiz_dyn'] = m

import quiz_dyn
print(quiz_dyn.x, quiz_dyn is m)
3. How many times is hi printed?
import importlib, sys, tempfile
from pathlib import Path

d = tempfile.mkdtemp()
sys.path.insert(0, d)
Path(d, 'quiz_hello.py').write_text("print('hi')\n")
importlib.invalidate_caches()
sys.modules.pop('quiz_hello', None)

import quiz_hello
import quiz_hello
_ = importlib.import_module('quiz_hello')
4. What does this print?
import sys
from cmath import phase

print('cmath' in sys.modules, 'cmath' in globals())
5. What does this print?
from cmath import *
from math import *

print(sqrt.__module__)
6. What does this print?
import importlib, sys, tempfile
from pathlib import Path

d = tempfile.mkdtemp()
sys.path.insert(0, d)
Path(d, 'quiz_rel.py').write_text('def f():\n    return 1\n')
importlib.invalidate_caches()
sys.modules.pop('quiz_rel', None)

import quiz_rel
from quiz_rel import f

Path(d, 'quiz_rel.py').write_text('def f():\n    return 22\n')
importlib.reload(quiz_rel)
print(f(), quiz_rel.f())
7. The file tools.py contains just print(__name__). What does it print when run with python tools.py, and when imported with import tools?
8. After import a.b.c, which of these names exist in the importing namespace?
9. What does this print?
import sys, types

m = types.ModuleType('quiz_all')
exec("__all__ = ['a', '_c']\na = 1\nb = 2\n_c = 3\n", m.__dict__)
sys.modules['quiz_all'] = m

ns = {}
exec('from quiz_all import *', ns)
print(sorted(k for k in ns if k != '__builtins__'))
10. Which statement about a directory plugins/ that has no __init__.py is true in Python 3?
11. Why prefer from .boolean import * over from common.validators.boolean import * inside common/validators/__init__.py?
12. You have lib.zip containing mypkg/__init__.py at the archive's root. What do you need to do so that import mypkg works?

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

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.

Hints (3)
  1. types.ModuleType(name) creates an empty module; its namespace is mod.__dict__.
  2. exec(code, namespace) runs code with namespace as its globals.
  3. Put the module in sys.modules before calling exec, 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 mod

Exercise 2: What would a star-import bring in?

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.

Hints (3)
  1. vars(module) (or module.__dict__) is the module's namespace.
  2. Use getattr(module, '__all__', None) to check for __all__ without an error.
  3. Note that an imported module (like math after import 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

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.

Hints (3)
  1. Use relative imports such as from .product import *; they don't depend on the package's name.
  2. A star-import respects each module's __all__, so _slug won't come along.
  3. After from .product import *, the sub-module itself is available as the name product inside __init__.py, so product.__all__ works.
Show a solution
INIT_SOURCE = '''
from .product import *
from .cart import *

__all__ = product.__all__ + cart.__all__
'''