缩短Python导入时间? [英] Shorten Python imports?

查看:39
本文介绍了缩短Python导入时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Django项目.我们称之为 myproject .现在,我的代码充满了 myproject.folder.file.function .无论如何,我是否可以删除所有导入内容的前缀,例如 myproject..如果我以后要重命名我的项目怎么办?当我要从中导入文件的那个文件位于同一项目中时,我需要为这些文件添加前缀,这让我很烦.没必要.

I'm working on a Django project. Let's call it myproject. Now my code is littered with myproject.folder.file.function. Is there anyway I can remove the need to prefix all my imports and such with myproject.? What if I want to rename my project later? It kind of annoys me that I need to prefix stuff like that when the very file I'm importing it from is inside that same project. Shouldn't be necessary.

推荐答案

来自myproject.folder导入文件(可怕的名字,顺便说一句,在内置类型 file 上践踏,但这是另一种说法;-),然后使用 file.function -如果 file (该模块名称必须 hate ;但也还是)很想你,添加例如 as fi from 语句,并使用 fi.function .如果您想将myproject重命名为myhorror,则只需触摸解决该问题的 from 语句即可(您可以使用相对导入,但这些导入会破坏2.5兼容性,因此目前禁止您使用App Engine-代价太高,至少给我带来了小小的便利;-).

from myproject.folder import file (horrible name, btw, trampling over the builtin type file, but that's another rant;-), then use file.function -- if file (gotta hate that module name;-) is still too long for you, add e.g. as fi to the from statement, and use fi.function. If you want to rename myproject to myhorror, you only need to touch the from statements addressing it (you could use relative imports, but those would break 2.5 compatibility and therefore ban you from App Engine for now -- too high a price to pay for minor convenience, for me at least;-).

编辑:如果几乎每个文件都需要某些给定的支持模块,这是确保支持模块位于sys.path上的目录(或zipfile)中的强大原因(可能值得即使只有30%的文件需要该支持模块也是如此!-).

Edit: if just about every file needs some given supporting module, that's a powerful reason for making sure that supporting module lives in a directory (or zipfile) that's on sys.path (it's probably worth doing even if, say, only 30% of the files need that supporting module!-).

这篇关于缩短Python导入时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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