New splat import proposal

Proposal:

# main.py
from utils.* import ClassFromA, ClassFromB, func_from_moreutils

Given the following directory/file structure:

  • utils/
    • A.py
    • B.py
    • moreutils.py
  • main.py

Assuming A, B, and moreutils all have multiple functions/classes in them, I want to be able to do from utils.* import ClassFromA, ClassFromB, func_from_moreutils.

Normally this would look like from utils.A import ClassFromA then from utils.B import ClassFromB finally from utils.moreutils import func_from_moreutils.

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

No response

Copied from: New splat import proposal · Issue #155186 · python/cpython · GitHub

That’s what the __init__.py is for. It lets you keep your internals structured without forcing that same, overly nested structure of imports on the user side.

# utils/__init__.py
from .A import ClassFromA
from .B import ClassFromB
from .moreutils import func_from_moreutils

Then just import utils; utils.ClassFromA(); utils.ClassFromB() or from utils import ClassFromA, ClassFromB, func_from_moreutils.

11 Likes

Though this will make for more idiomatic and shorter code in a subset of cases, that subset is too small. No symbols may collide (no two submodules have the same attribute) and the order of fetching the symbols cannot matter (since attribute access can be overridden to have dynamic behaviour that changes the state of the program).

1 Like