thaking
thaking

Reputation: 3635

Python: universal import

Can anyone explain which 'import' is universal, so I don't need to write for example:

from numpy import *
import numpy
import numpy as np
from numpy.linalg import *

Why not import numpy or from numpy import * to incude all from "numpy"?

Upvotes: 2

Views: 9612

Answers (1)

Michael Edenfield
Michael Edenfield

Reputation: 28338

I'm not sure what you mean by "all from numpy", but you should never need to use more than one form of import at a time. They do different things:

Option One: import

import numpy will bring the entire numpy module into the current namespace. You can then reference anything from that moudule as numpy.dot or numpy.linalg.eig.

Option Two: from ... import *

from numpy import * will bring all of the public objects from numpy into the current namespace as local references. If the package contains a list named __all__ then this command will also import every sub-module defined in that list.

For numpy this list includes 'linalg', 'fft', 'random', 'ctypeslib', 'ma', and 'doc' last I checked. So, once you've run this command, you can call dot or linalg.eig without the numpy prefix.

If you're looking for an import that will pull every symbol from every submodule in the package into your namespace, then I don't think there is one. You would have to do something like this:

from numpy.linalg import *
from numpy.fft import *
from numpy.random import *
from numpy.ctypeslib import *
from numpy.ma import *
from numpy import *

which is, I think, what you're trying to avoid.

Upvotes: 9

Related Questions