简体   繁体   English

“嵌套”导入语句的Python性能影响

[英]Python performance effects of 'nested' import statements

I have a program spread across 2 files using the twitter api. 我有一个使用twitter api分布在2个文件中的程序。 One file is dedicated to sending and reading tweets, so I have put the 'import twitter' line in that file. 一个文件专用于发送和读取推文,因此我在该文件中放入了“ import twitter”行。 The second file has an import statement to import this twitter-based file and will call the "read" and "post" functions from that file. 第二个文件具有导入语句,用于导入此基于Twitter的文件,并将从该文件调用“读取”和“发布”功能。

This is the gist of the code: 这是代码的要点:

File 1: 文件1:

import file2
file2.post(some text)

File 2: 档案2:

import twitter
api = twitter.Api(...)
def post(text):    
    api.PostUpdate()

This works fine and acts exactly as I expect it to, but I'm not sure if this is the most efficient way, performance wise, of running this. 这可以正常工作,并且完全符合我的预期,但是我不确定这是否是运行此方法的最有效方式(从性能角度考虑)。 Will the 'import twitter' line be run every time file 2 is called and fill up memory and time with duplicate imports? 每次调用文件2时都会运行“ import twitter”行,并使用重复的导入来填充内存和时间吗? And if so, would I be better with this: 如果是这样,我会更好一点:

File 1: 文件1:

import twitter
import file2
api = twitter.Api(...)
file2.post(some text, api)

File 2: 档案2:

def post(text, api):
    api.PostUpdate(text)

Where the api object is being passed across files. 跨文件传递api对象的位置。

Thanks 谢谢

Import caches all imports, so with multiple imports they will just access the cached version after the first time an import is performed. 导入会缓存所有导入,因此对于多个导入,它们将在首次执行导入后才访问缓存的版本。 See https://docs.python.org/3/reference/import.html for details of how this works. 有关其工作原理的详细信息,请参见https://docs.python.org/3/reference/import.html

Generally speaking you should create your import structure around the concept of modules being correct, performance shouldn't be a large factor in this decision, because honestly when you get the import structure right there won't be that much of a performance difference. 一般而言,您应该围绕正确的模块概念创建导入结构,性能不应成为决定该决定的重要因素,因为说实话,正确地导入结构不会带来太大的性能差异。 If you use something from a module in a file you should explicitly import that module. 如果您使用文件中某个模块中的内容,则应显式导入该模块。 Related to this make sure that every module you use can be imported directly without error, this will help you design your modules better and avoid a class of subtle bugs where changing the order of importing can cause errors due to the caching mechanism in importlib. 与此相关的是,确保可以直接导入使用的每个模块而不会出错,这将帮助您更好地设计模块,并避免一类细微的错误,这些错误会由于importlib中的缓存机制而导致更改导入顺序而导致错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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