简体   繁体   中英

Question regarding Python namespaces and function imports: Is it preferable to import only the function you need from a module?

So I don't recall where I heard this or read this, but I remember being instructed that it was best practice to import only the needed functions or classes from modules for several reasons.

We should do this

from my_module import (needed_function, NeededClass)
from numpy import (arange, nditer, ones, zeros, array ndarray)

needed_function()
NeededClass()

ones
arange(0,16).reshape(4,4)
#etc etc

rather than import the module and calling the needed functions

import my_module as mm
import numpy as np

mm.needed_function()
mm.NeededClass()

np.ones
np.arange(0,16).reshape(4,4)
#etc etc

I was told that the primary reason is that when module.function is called Python must search the local namespace for module then search the module's namespace for function , then continue. This must be done each time module.function is called and is potentially very time wasting (for large computations).

The contrasts with directly importing the function because then python only needs to search the local namespace once for that function, a much smaller task than searching a potentially very large namespace, such as numpy or scipy.

Is this correct?

Some good answers: https://softwareengineering.stackexchange.com/questions/187403/import-module-vs-from-module-import-function

Personally for my use case, I'm creating an.exe that needs to be very portable and as small file size as possible. Because of that, I mostly import only single functions where possible.

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