fromAdvanced Examples

Used with import to bring in specific names from a module

from with __all__ and __init__

Controlling what 'from module import *' exposes.

python
# __all__ controls star imports
# In a module, define:
# __all__ = ["public_func", "PublicClass"]

# Simulate a module with __all__
import types
mod = types.ModuleType("mymod")
mod.__all__ = ["greet", "farewell"]
mod.greet = lambda: "hello"
mod.farewell = lambda: "goodbye"
mod._internal = lambda: "secret"

public = [name for name in mod.__all__]
print(f"Public API: {public}")

# from ... import * respects __all__
# Without __all__, all non-underscore names are imported
all_names = [n for n in dir(mod) if not n.startswith("_")]
print(f"All public names: {all_names}")

# Lazy imports with importlib
from importlib import import_module
json = import_module("json")
print(json.dumps({"lazy": True}))

__all__ is a list of strings defining the public API. 'from module import *' only imports names in __all__ if it exists, otherwise all non-underscore names.

Want to try these examples interactively?

Open Advanced Playground