Reputation: 4187
Suppose I have a code like this in module a.py
import numpy as np
def sqrt(x):
return np.sqrt(x)
And I have a module b.py
written like this:
import a
print(a.sqrt(25))
print(a.np.sqrt(25))
I will see that the code runs fine and that when using autocomplete in most IDEs, I found that a.np
is accessible. I want to make a.np
private so that only a
code can see that variable.
I don't want b
to be able to access a.np
.
What is a good approach to make this possible?
Why do I want a.np
to be inaccessible? Because I want it to not show in the autocomplete when I type a.
and press Tab in Jupyter Lab. It hides what the modules can do because there are so many imports that I use in my module.
Upvotes: 1
Views: 209
Reputation: 10971
I see 2 approaches here:
more user-friendly solution: change alias names to "underscored" ones
import numpy as _np
...
this will not prevent from importing it, but it will say to user that this are implementation details and one should not depend on them.
preferred-by-me solution: do nothing, leave it as it is, use semver and bump versions accordingly.
Upvotes: 0
Reputation: 77912
The solution is the same as for "protected" attributes / methods in a class (names defined in a module are actually - at runtime - attributes of the module object): prefix those names with a single leading underscore, ie
import numpy as _np
def sqrt(x):
return _np.sqrt(x)
Note that this will NOT prevent someone to use a._np.sqrt(x)
, but at least it makes it quite clear that he is using a protected attribute.
Upvotes: 2