Imports and Modules
Imports and Modules
Section titled βImports and ModulesβWhat it means
Section titled βWhat it meansβimport brings a moduleβs names into your namespace. A module is any .py file; a package is a directory of modules with an __init__.py. __all__ is a module-level list of strings that controls exactly what from module import * pulls in β it doesnβt affect explicit imports like from module import specific_name.
Examples
Section titled βExamplesβimport math # module import β access via math.sqrt(...)from math import sqrt # name import β access via sqrt(...) directlyfrom math import sqrt as s # aliased importimport numpy as np # conventional aliasing for a common libraryfrom .utils import helper_functionfrom .models import User# now `from mypackage import helper_function, User` works directly__all__ = ["compute_average", "compute_median"]
def compute_average(values): ...
def compute_median(values): ...
def _internal_helper(): # not in __all__, and leading underscore signals "private" ...from analytics import *# imports compute_average, compute_median only# _internal_helper is NOT imported, even without __all__, because of the leading underscoreCommon mistake
Section titled βCommon mistakeβAssuming __all__ (or a leading underscore) makes a name truly private. Itβs a convention, not enforcement β from analytics import _internal_helper and import analytics; analytics._internal_helper() both still work fine. __all__ only changes what import * grabs.
__all__ = ["compute_average"]
def _internal_helper(): return "not actually private"
# elsewhere:from analytics import _internal_helper # works! __all__ didn't block thisprint(_internal_helper()) # "not actually private"Quick practice
Section titled βQuick practiceβ-
What does
__all__actually control?Answer
Only what `from module import *` imports β it has no effect on explicit `from module import name` or `import module; module.name`. -
Does a name starting with
_get blocked from being imported?Answer
No β it's only excluded from `import *`. You can still explicitly `from module import _private_name`; Python doesn't enforce true privacy. -
Why would you re-export names in a packageβs
__init__.py?Answer
To give users a flatter public API β `from mypackage import User` instead of requiring `from mypackage.models import User`, hiding the internal module layout.