Skip to content

Imports and Modules

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.

import math # module import β€” access via math.sqrt(...)
from math import sqrt # name import β€” access via sqrt(...) directly
from math import sqrt as s # aliased import
import numpy as np # conventional aliasing for a common library
mypackage/__init__.py
from .utils import helper_function
from .models import User
# now `from mypackage import helper_function, User` works directly
analytics.py
__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 underscore

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.

analytics.py
__all__ = ["compute_average"]
def _internal_helper():
return "not actually private"
# elsewhere:
from analytics import _internal_helper # works! __all__ didn't block this
print(_internal_helper()) # "not actually private"
  1. What does __all__ actually control?

    AnswerOnly what `from module import *` imports β€” it has no effect on explicit `from module import name` or `import module; module.name`.
  2. Does a name starting with _ get blocked from being imported?

    AnswerNo β€” it's only excluded from `import *`. You can still explicitly `from module import _private_name`; Python doesn't enforce true privacy.
  3. Why would you re-export names in a package’s __init__.py?

    AnswerTo give users a flatter public API β€” `from mypackage import User` instead of requiring `from mypackage.models import User`, hiding the internal module layout.