# __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 indir(mod) ifnot n.startswith("_")]
print(f"All public names: {all_names}")
# Lazy imports with importlibfrom importlib import import_module
json = import_module("json")
print(json.dumps({"lazy": True}))
Output
Click "Run" to execute your code
__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.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?