Python · The language, not just syntax
How does the Python import system work?
Short answer
An import searches sys.path through finders, loads the module once into sys.modules, and binds a name in the importing scope. A package is a module with submodules, often marked by __init__.py.
The import statement first checks sys.modules, so a module is executed only once per process. If it is missing, finders search the path entries, loaders create the module object, and the code runs. The result is cached, which is why later imports are cheap.
from billing.services import charge
if __name__ == "__main__":
charge(1500)Packages and layout
- __init__.py marks a regular package and can expose a public API
- Absolute imports are clearer and avoid ambiguity: from billing import charge
- Relative imports work inside a package but are harder to read from outside
- Namespace packages omit __init__.py and merge directories across path entries
Circular imports usually indicate a design problem. They can often be fixed by moving the shared code to a lower-level module, importing inside a function, or using type-only imports under TYPE_CHECKING. Import-time work such as network calls makes startup slow and tests brittle.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the role of sys.modules?
- 2What is the difference between a module and a package?
- 3How do you break a circular import?
- 4Why does running a file directly sometimes break imports?
Say it in the interview
An import checks sys.modules first, then searches sys.path through finders, executes the module once and caches it. A package is essentially a module with submodules, and __init__.py can define its public surface. I prefer absolute imports and a clear layout. Circular imports usually point to a design problem, so I move shared code lower or use a local or type-only import.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.