Python / Core Python Fundamentals Interview Questions
How do Python modules and imports work?
A module is any .py file. Importing it executes the file (once per interpreter session; subsequent imports reuse the cached version from sys.modules) and makes its names available in the importing namespace.
# Importing the whole module â access via module.name import math print(math.sqrt(16)) # 4.0 # Importing specific names â available without prefix from math import sqrt, pi print(sqrt(25)) # 5.0 # Import with alias â avoid name clashes or shorten long names import numpy as np import pandas as pd # Star import â pulls all public names (avoid in production code) from math import *
Python looks for modules in this order: (1) built-in modules compiled into the interpreter, (2) sys.modules cache, (3) directories listed in sys.path — which includes the directory of the script being run, PYTHONPATH env var locations, and site-packages.
A package is a directory containing an __init__.py file (can be empty). Nested packages create a hierarchy: from mypackage.utils import helper. Python 3.3+ introduced namespace packages (no __init__.py needed), but regular packages with __init__.py are still the norm.
The if __name__ == '__main__': guard at the bottom of a module lets you write code that runs when the file is executed directly but not when imported as a module. It is the standard way to write both importable modules and runnable scripts in the same file.
More Related questions...