What is Python's import system and __init__.py?
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.
Previous
What is Python's async generators and async context managers?
Next
What is Python's performance optimization techniques?