A developer creates a package named 'analytics' with the following structure:
analytics/ __init__.py stats.py models/ __init__.py regression.py
The developer wants the statement 'from analytics import *' to import only the functions 'mean' and 'std' from stats.py. What should be added to analytics/__init__.py?
Trap 1: Nothing; by default, all names are exported.
Merely relying on the default import-star behavior does not populate the `analytics` package namespace. When a package is imported, Python executes its `__init__.py`, but unless that file contains an explicit `import` or `from ... import` statement, no submodule names (like `mean` or `std`) are bound as attributes of the package. Therefore, `from analytics import *` would find nothing to import, even though Python normally exports all names not starting with an underscore when `__all__` is absent.
Trap 2: __all__ = ['stats.mean', 'stats.std']
This uses dotted paths in `__all__`, which is invalid because Python looks for simple attribute names in the namespace. `stats.mean` is not a valid attribute name, so this would cause an error or import nothing.
Trap 3: __all__ = ['mean', 'std']
Setting `__all__ = ['mean', 'std']` alone is insufficient because the names `mean` and `std` are not defined in the `analytics` package namespace without an explicit import. Thus, `from analytics import *` would not be able to find them.
- A
Nothing; by default, all names are exported.
Why it fails: Merely relying on the default import-star behavior does not populate the `analytics` package namespace. When a package is imported, Python executes its `__init__.py`, but unless that file contains an explicit `import` or `from ... import` statement, no submodule names (like `mean` or `std`) are bound as attributes of the package. Therefore, `from analytics import *` would find nothing to import, even though Python normally exports all names not starting with an underscore when `__all__` is absent.
- B
from analytics.stats import *
This imports all public names from `stats.py` into the `analytics` package namespace, making `mean` and `std` available. However, it imports all other names as well, so it does not satisfy the 'only' requirement. It is the necessary first step, but additional control (like `__all__`) would be needed to limit exports.
- C
__all__ = ['stats.mean', 'stats.std']
Why it fails: This uses dotted paths in `__all__`, which is invalid because Python looks for simple attribute names in the namespace. `stats.mean` is not a valid attribute name, so this would cause an error or import nothing.
- D
__all__ = ['mean', 'std']
Why it fails: Setting `__all__ = ['mean', 'std']` alone is insufficient because the names `mean` and `std` are not defined in the `analytics` package namespace without an explicit import. Thus, `from analytics import *` would not be able to find them.