What is Python's import system and __init__.py?
Why Interviewers Ask This
Advanced questions like this reveal whether a candidate has internalized Python deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.
Answer
Python's import system works through several steps: Python searches sys.modules (cache), then sys.path (list of directories). The __init__.py file marks a directory as a package and is executed when the package is imported — use it to define the public API with __all__ and make submodule contents available at the package level. Relative imports: from . import sibling, from ..parent import module. Lazy imports: defer expensive imports to first use, avoiding slow startup. Custom importers: implement importlib.abc.MetaPathFinder and MetaPathLoader for importing from databases, encrypted files, or URLs. importlib.import_module(name): dynamic import by string name. __all__: controls what from module import * exports. Circular imports: common in large projects — resolve by restructuring, using local imports, or importing inside functions.
Common Mistake
Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your Python experience.
Previous
What is Python's async generators and async context managers?
Next
What is Python's performance optimization techniques?