0

I use numpy for my customized functions stored in my module. Is it true that the package numpy will be automatically imported into the file in which I call my module? Can I make the package numpy only available for the function defined in my module but not the file which calls my module?

1 Answer 1

1

When you call import numpy in your module then, yes, it is only available within your module and not from whatever module happens to import yours. There is nothing stopping the outer module from importing numpy itself, though, as it must be installed on the system for you to import it yourself.

ETA:

Demonstration:

In inner.py:

import numpy as np
print ("Inner: ", np.__version__)

In outer.py:

import inner
print ("Outer: ", np.__version__)

Outputs:

$ python outer.py
('Inner: ', '1.9.2')
Traceback (most recent call last):
  File "outer.py", line 3, in <module>
    print ("Outer: ", np.__version__)
NameError: name 'np' is not defined

ETA:

This could happen if you imported your module with a wildcard (from inner import *). PEP8 discourages this:

Wildcard imports (from <module> import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).

Sign up to request clarification or add additional context in comments.

7 Comments

I asked this question, because in my module, I import numpy as np. In my main file, in which my module is imported, it does not need to import numpy separately. Functions from numpy can be called from np. directly. This caught my attention.
I'm afraid you must have something else going on, are you certain that the outer module doesn't import np as well? Look at the demo code I added to my answer.
I guess because I used from my_module import * ?
Ah, yes, that would do it. You shouldn't do that. :-)
Thanks a lot. It is clear now. So it means I can also import all package in my module to clean up my main file then?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.