简体   繁体   中英

Pythonic way to import modules from packages

Is there any difference, subtle or not so subtle, between the effects of the following import statements? I have found both used in example programs and sure enough, they both seem to work. It would go against the grain of Python's "there is only one way to do stuff" if they were totally equivalent in function, so I'm puzzled. I'm just starting out in Python and trying to keep good habits. So for instance, for the interpolate module in the scipy package ...

from scipy import interpolate as spi

or

import scipy.interpolate as spi

both appear to put the interpolate module in the current namespace as spi

No, there is no difference between the two statements, both put the exact same object into your module namespace ( globals() ), under the exact same name.

They go about it in slightly different ways but the end-result is the same.

Essentially, the first does:

from scipy import interpolate
spi = interpolate
del interpolate

and the second comes down to

import scipy.interpolate
spi = scipy.interpolate
del scipy

and in the end all you have is the spi name bound to the interpolate function.

Personally, I would not rename the function like that, I'd keep it as import scipy and use scipy.interpolate , clearly communicating where the object comes from throughout the code, or I'd use from scipy import interpolate .

Renaming the object may make it easier to type for you, but may make it harder for you or others to grok later on when you revisit this code after months of absence.

It's a matter of taste, really.

In this particular case, I would use import scipy.interpolate as spi , to remember that interpolate is a submodule of scipy . If I were to import a function from a module, I would use from module import function .

The only thing is, be consistent with the convention you choose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM