I am working on a pretty huge Python package. Inside several modules, different programmers import other modules to do calculations. For the sake of this discussion, let's stick to numpy
.
Common practice, when importing modules is defining an alias for easier programming, so let's say in a module foo.py
there is a line doing
import numpy as np
So there will be a foo.np
namespace. I also found out, that by deleting the reference to np
inside foo.py
by doing
del np
at the end of the module seems to clear the namespace as well.
As a maintainer of a huge package, I like this way of keeping the namespace clean but I wonder if this is good programming practice or if there are problems arising especially if my package has a module bar.py
in the same level as foo.py
which also uses the same external numpy
module? If yes, is there a simple and better way to keep the namespaces of foo
and bar
clean or is this housekeeping of namespaces itself a bad idea?
Here is a simple example:
foo.py
:
import numpy as np
def foo(x):
"""Return 2D square array of zeros."""
return np.zeros((x, x))
del np
bar.py
:
import numpy as np
def bar():
"""Return 3x3 square array."""
return np.arange(9).reshape(3, 3)
main.py
:
from bar import bar
from foo import foo
print bar()
print foo(3)
And here are the outputs:
[[0 1 2]
[3 4 5]
[6 7 8]]
Traceback (most recent call last):
File "/Users/jonrsharpe/Documents/main.py", line 6, in <module>
print foo(3)
File "/Users/jonrsharpe/Documents/foo.py", line 5, in foo
return np.zeros((x, x))
NameError: global name 'np' is not defined
So clearly this has not affected bar.py
(which you should expect - del
removes that reference, but doesn't affect the underlying object) but has broken the functionality imported from foo.py
, as np
is no longer accessible to the objects defined in that file.
is this housekeeping of namespaces itself a bad idea?
I'm not sure what you see as the benefits of it. Removing names from the namespace of a module you've finished using is not going to save very much (if any) space, and the underlying imported module (numpy
, in this case) will still be in sys.modules
.
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