Importing module implicitly
Question: In a directory, I have two files: `A.py`, and `B.py`. Here is their content:

    
    
    # A.py
    
    import numpy
    x = numpy.array([1, 2, 3])
    print x
    
    # B.py
    
    import A
    y = numpy.array([4, 5, 6])
    print y
    

From Command Prompt (Windows 8), I run the following command:

    
    
    python A.py
    

which gives the output:

    
    
    [1, 2, 3]
    

But when I run the following command:

    
    
    python B.py
    

I get the output:

    
    
    NameError: name 'numpy' is not defined
    

Why is this? Shouldn't numpy be imported implicitly into B via A?


Answer: When you do

    
    
    import A
    

That brings in all of the exportable functions and variables from the file
`A.py` in, but with the namespace prefix of `A`

Assuming you don't want to do the import of numpy again in B (the normal
option), your code then needs to be one of

    
    
    import A
    y = A.numpy.array([4, 5, 6])
    

Or:

    
    
    from A import *
    

The former gets `numpy` via A, with the prefix of A (since that's where it was
first imported), the latter explicitly imports all the things from A without a
new prefix. The downside of the latter is it can bring in the rest of the
kitchen sink too, so isn't generally a good plan for complex modules.

Normally though, if B needs numpy, it would import that directly. If A is
making some changes to a module that it then exports, you would normally
expect to import and reference it explicitly, to flag up to everyone looking
at the code later that you're not dealing with the regular version of the
library.

