Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What is a Module in Python?
What you need to know
Terms
- Module — one
.pyfile.utils.pyis the moduleutils. - Package — a folder of modules, imported with dots:
rag.chunking. - Library — an informal word for a package you install, like
requestsorpandas. - Namespace — each module has its own;
utils.cleanandother.cleannever collide.
What happens on import
1import sys, pathlib23pathlib.Path("textutils.py").write_text(4 'print("textutils loading...")\n'5 'def clean(text):\n'6 ' return " ".join(text.split()).lower()\n',7 encoding="utf-8",8)9sys.path.insert(0, ".") # make sure the current folder is searched1011import textutils # prints: textutils loading...12import textutils # prints nothing: already in sys.modules13print(textutils.clean(" Refund PENDING ")) # refund pending14print("textutils" in sys.modules) # True- Python checks the cache,
sys.modules. If the module is there, it is reused. - Otherwise it searches the folders in
sys.path, in order: the running script's folder first, thenPYTHONPATH, then the standard library, thensite-packages, where pip installs things. - It runs the file's top-level code once, top to bottom, and stores the module object in the cache.
Because top-level code runs at import time, modules should mostly define things, not do things. Scripts put their actions under if __name__ == "__main__":.
A typical project layout
support_bot/ rag/ __init__.py loaders.py # read PDFs, CSVs chunking.py # split text prompts.py # prompt templates app.py # from rag.chunking import split_textA real-life example
A beginner writes their first LLM script and saves it as openai.py. It starts with import openai. Because the script's own folder is searched first, Python imports the script itself instead of the installed SDK, and the run fails with an error like AttributeError: partially initialized module 'openai' has no attribute 'OpenAI' (most likely due to a circular import). The same happens with files named json.py, random.py, csv.py or langchain.py.
The fix is to rename the file (for example, chat_demo.py) and delete any __pycache__ it left behind. Python 3.13 and later even add a hint to the error message suggesting the rename, but knowing why — the search order of sys.path — is what the interviewer is checking.
Follow-up questions to expect
- "What is the difference between a module and a package?" — A module is one
.pyfile; a package is a folder of modules that you import with dotted names. - "What happens if you import a module twice?" — It runs only once. The second import returns the cached object from
sys.modules.importlib.reload()forces a re-run. - "What is
__init__.pyfor?" — It marks a folder as a regular package and runs when the package is imported, often to expose a clean public API.