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?
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:
import this.__all__ variable to define exactly what should be imported when the module is wildcard-imported. See Can someone explain __all__ in Python?If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With