Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__init__.py imports expose also modules I use, not only my own classes [duplicate]

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?

like image 439
Lester Jack Avatar asked Nov 15 '25 23:11

Lester Jack


1 Answers

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?
like image 146
Erik Cederstrand Avatar answered Nov 17 '25 18:11

Erik Cederstrand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!