Interview Questions
Modules and Packages · Study material
Modules and Packages – Interview Questions
1. What is a module in Python?
A .py file containing definitions and statements that can be imported.
2. What is a package?
A directory of modules (usually with __init__.py) that can contain sub-packages.
3. Difference between import x and from x import y?
import x binds the module name and you write x.y; from x import y binds y directly in your namespace.
4. What happens when a module is imported twice?
Its code runs only the first time; afterwards the cached module from sys.modules is returned.
5. How does Python find a module?
It checks sys.modules, then searches the directories in sys.path in order (script directory, PYTHONPATH, standard library, site-packages).
6. What does if __name__ == "__main__" do?
Runs the code under it only when the file is executed directly, not when it is imported.
7. What is __init__.py for?
It marks a regular package and runs when the package is imported; it can initialise the package and re-export names.
8. What are relative imports?
Imports relative to the current package, such as from . import utils or from ..models import User; they only work inside packages.
9. What is __all__?
A list of public names that from module import * imports.
10. How do you reload a module?
importlib.reload(module).
11. What is a virtual environment?
An isolated Python environment with its own site-packages, created with python -m venv, so projects can use different package versions.
12. Why is from module import * discouraged?
It hides where names come from and can silently overwrite existing names, including built-ins.
13. What does dir(module) return?
A sorted list of the names defined in the module.
14. How do you import a module whose name is in a string?
importlib.import_module(name).
15. What is the difference between ImportError and ModuleNotFoundError?
ModuleNotFoundError (a subclass) means the module itself was not found; ImportError also covers a module that exists but lacks the requested name.