Best way to import modules in Python

a 夏天 提交于 2019-12-12 04:54:49

问题


Is there a performance disadvantage when importing all module functions into the namespace at once, as in:

from numpy import *
A = array([...])

compared to only importing the module function when you need to use it, as in:

import numpy as np
A = np.array([...])

回答1:


It won't have any noticeable effect on performance. It does pollute the module's namespace with a bunch of functions that may shadow built-ins (for example, numpy include its own sum implementation), and in general it makes it hard to tell where functions are actually defined, so you should avoid it.




回答2:


from numpy import * would make every imported method/variable appear to be as an integral part of your code. There will be no way to say if the imported bits came from "outside" or if they are defined within your code. I don't think it is performance issue but rather than a debugging and so-called "namespacing" which is an entire subject on its own. When you use import numpy as np you make sure that np is used as a "nickname" so imported code doesn't become "fantom". So when there is a need to trace or to track down where a particular method/function/variable defined or came from it would be relatively easy or possible to do since `np' would be used as a clue.



来源:https://stackoverflow.com/questions/23810425/best-way-to-import-modules-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!