2

There's something that I'm not grasping about python imports. I've read dozens of articles but I'm not finding a satisfactory answer. The situation is this:

I'm writing a package made of several modules. Let's say that the package is named pack1. In the __init__.py file, in order to expose the classes and functions I defined in my modules, I wrote:

    from .module1 import *
    from .module2 import *
    ...

Now, in module 1:

    from math import sqrt  # a tool that I need

    class class1:
         <body>

    class class2:
         <body>
    ....
    class class100:
         <body>

My problem is that when I

    import pack1

in another project, I see sqrt in pack1's namespace. Do I have to import each one of the 100 classes separately in the __init__.py file in order to avoid this and keep my namespace clean? Do I have to do some hack with the inspect module in __init__.py in order to identify the classes that were defined and not imported (I think this would be very ugly)? Or, as I suspect, I'm mistaking something about how I should handle the module structure or the import statements?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Lester Jack
  • 179
  • 8
  • 1
    Why wouldn't you? It *is* in that namespace. See e.g. https://docs.python.org/3/tutorial/modules.html#importing-from-a-package – jonrsharpe Apr 17 '18 at 07:15
  • Yes, I expressed myself badly; I know that things are working exactly as intended, my question was how to do a clean wildcard import, since I want to import many names and import them explicitly would be tedious. – Lester Jack Apr 17 '18 at 07:24
  • You are explaining one of the causes why wildcard imports are considered bad practice by many Python developers. – Klaus D. Apr 17 '18 at 07:25

1 Answers1

4

Wildcard imports import everything defined in the global namespace in that module. It does not discriminate between "local" classes, modules that were imported, functions or variables.

There are two ways around this:

  1. Import exactly what you want, instead of using wildwards. Explicit is better than implicit, according to import this.
  2. Use the special __all__ variable to define exactly what should be imported when the module is wildcard-imported. See Can someone explain __all__ in Python?
Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63
  • 2
    The `__all__` variable was the piece that I was missing to elegantly handle wildcard imports. Thank you very much! – Lester Jack Apr 17 '18 at 07:18