Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does importing a Python file also import the imported files into shell?

I am running Python 3.6.2 and trying to import other files into my shell prompt as needed. I have the following code inside my_file.py.

import numpy as np
def my_file(x):
    s = 1/(1+np.exp(-x))
    return s

From my 3.6.2 shell prompt I call

from my_file import my_file

But in my shell prompt if I want to use the library numpy I still have to import numpy into the shell prompt even though I have imported a file that imports numpy. Is this functionality by design? Or is there a way to import numpy once?

like image 371
Riskinit Avatar asked Sep 10 '18 01:09

Riskinit


1 Answers

import has three completely separate effects:

  1. If the module has not yet been imported in the current process (by any script or module), execute its code (usually from disk) and store a module object with the resulting classes, functions, and variables.
  2. If the module is in a package, (import the package first, and) store the new module as an attribute on the containing package (so that references like scipy.special work).
  3. Assign the module ultimately imported to a variable in the invoking scope. (import foo.bar assigns foo; import baz.quux as frob assigns baz.quux to the name frob.)

The first two effects are shared among all clients, while the last is completely local. This is by design, as it avoids accidentally using a dependency of an imported module without making sure it’s available (which would break later if the other modules changed what they imported). It also lets different clients use different shorthands.

As hpaul noted, you can use another module’s imports with a qualified name, but this is abusing the module’s interface just like any other use of a private name unless (like six.moves, for example, or os.path which is actually not a module at all) the module intends to publish names for other modules.

like image 139
Davis Herring Avatar answered Nov 01 '22 06:11

Davis Herring