Modules and Packages Flashcards
7 cards from real Python practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 7 Modules and Packages flashcards as text
What is `sys.modules`?
Answer: A dictionary caching all currently imported modules
`sys.modules` is a dict mapping module names to module objects; Python checks it first on every import to avoid re-executing module code.
What does `pkgutil.iter_modules()` return?
Answer: An iterator of `(finder, name, ispkg)` tuples for modules in given paths
`pkgutil.iter_modules(path)` yields named tuples describing each module or subpackage found in the given list of directories.
Which attribute of a module object stores the file path where the module was loaded from?
Answer: __file__
`module.__file__` is the absolute path to the `.py` (or `.pyc`) file that was executed to create the module.
When is `__init__.py` code executed?
Answer: The first time the package or any of its submodules is imported
`__init__.py` runs once on the first import of the package; subsequent imports use the cached module from `sys.modules`.
What is the difference between a regular package and a namespace package?
Answer: A regular package has `__init__.py`; a namespace package does not and can span multiple directories
Regular packages require `__init__.py`; namespace packages (PEP 420) lack it and allow merging directories across multiple locations into one logical package.
What does setting `sys.path.insert(0, '/my/path')` accomplish?
Answer: Makes Python search `/my/path` before all other directories when importing
Inserting at index 0 places the path at the front of `sys.path`, so Python finds modules there before any other location.
Which built-in function returns a list of names defined in a module?
Answer: dir()
`dir(module)` returns a sorted list of names in the module's namespace, including functions, classes, and variables.