哪个是更好的做法-全球进口还是本地进口 [英] Which is a better practice - global import or local import

查看:58
本文介绍了哪个是更好的做法-全球进口还是本地进口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在django中开发一个应用程序,并且我怀疑在全局级别导入库是否会比在本地(按功能)级别导入对内存或性能有任何影响.如果是按功能或视图导入的,则仅导入所需的模块即可节省空间,对吗?还是这样做有负面影响?

I am developing an app in django and I had a doubt if importing a library at the global level has any impact over the memory or performance than importing at the local ( per-function) level. If it is imported per function or view, the modules that are needed alone are imported saving space right? Or are there any negatives in doing so?

推荐答案

您肯定已经注意到几乎所有的Python代码都在文件顶部进行导入.这是有原因的:导入的开销很小,并且可能是您将始终在流程生命周期中的某个时候导入代码,所以您最好也不要这样做.

You surely must have noticed that almost all Python code does the imports at the top of the file. There's a reason for that: the overhead of importing is minimal, and the likelihood is that you will be importing the code at some point during the process lifetime anyway, so you may as well get it out of the way.

在函数级别导入的唯一好理由是避免循环依赖.

The only good reason to import at function level is to avoid circular dependencies.

编辑.您的评论表明,至少在Python中,您不了解网络应用的总体运行方式.他们不会为每个请求启动新流程,也不会从头开始导入代码.而是,服务器根据需要实例化进程,并且每个进程都会处理许多请求,直到最终将其终止.因此,在此生命周期中,很可能最终将需要所有进口.

Edit Your comments indicate you haven't understood how web apps generally work, at least in Python. They don't start a new process for each request and import the code from scratch. Rather, the server instantiates processes as required, and each one serves many requests until it is finally killed. So again it is likely that during that lifetime, all the imports will end up being needed.

这篇关于哪个是更好的做法-全球进口还是本地进口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆