[英]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.有人告诉我,主要原因是当
module.function
被调用时 Python 必须在本地命名空间中搜索module
,然后在模块的命名空间中搜索function
,然后继续。 This must be done each time module.function
is called and is potentially very time wasting (for large computations).这必须在每次调用
module.function
时完成,并且可能非常浪费时间(对于大型计算)。
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.与直接导入 function 形成对比,因为 python 只需要为该 function 搜索本地命名空间一次,这比搜索可能非常大的命名空间(例如 numpy 或 scipy)要小得多。
Is this correct?这样对吗?
Some good answers: https://softwareengineering.stackexchange.com/questions/187403/import-module-vs-from-module-import-function一些好的答案: 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.就我个人的用例而言,我正在创建一个 .exe,它需要非常便携并且文件大小尽可能小。 Because of that, I mostly import only single functions where possible.
因此,我大多只在可能的情况下导入单个函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.