Python 中的自动加载

发布于 2024-07-25 07:14:46 字数 1432 浏览 5 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

轻许诺言 2024-08-01 07:14:46

“延迟导入”可以构建在 PEP 302 中指定的“导入钩子”之上,现已全面实施。 PEP 369 曾经涵盖“惰性导入”以及导入后挂钩,但后来进行了简化,现在仅涵盖导入后挂钩; 不过,您可能对原始草案感兴趣。

通过 meta_path 钩子实现“延迟导入”的良好实现可以在 中找到这个食谱

"Lazy imports" could be built on top of the "import hooks" specified in PEP 302, and now fully implemented. PEP 369 used to cover "lazy imports" as well as post-import hooks, but has since been simplified and now only covers post-import hooks; still, you might be interested in the original draft.

A good implementation of "lazy imports" via the meta_path hook can be found in this recipe.

尝蛊 2024-08-01 07:14:46

回答使用类来模拟模块的问题:

是的,该功能并非偶然。 它从 2.x 系列早期就已经存在,并且在 3.x 系列中仍然有效。

回答延迟加载的问题:

有几种方法可以做到这一点,每种方法都有点神秘。 使用模块模拟器是一个很好的方法。

To answer the question of using a class to impersonate a module:

Yes, the functionality is not accidental. It has been there since early in the 2.x series and still works in the 3.x series.

To answer the question of lazy loading:

There are several ways to do it, and each one is going to be a bit mysterious. Using a module impersonator is a fine method.

爱的十字路口 2024-08-01 07:14:46

不,我认为这没有用。

为什么要为您尝试从模块获取的每个属性动态创建一个函数? 我似乎很困惑。 看起来新功能正在神奇地创建,因此必须深入研究实现才能了解发生了什么。 所有这些都没有语法上的好处。

即使您有充分的理由这样做,为什么要使用模块呢? 为什么要在 sys.modules 中注册类实例? 我认为让事情看起来不像它们本来的样子在Python中是不受欢迎的。

除非你故意混淆代码,否则我不明白为什么有人会这样做。

No, I don't think that's useful.

Why create a function on the fly for every attribute you're trying to get from the module? Seems confusing to me. It appears that new functions are being created by magic so one has to look deep into the implementation to understand what is going on. And all that for no syntactical benefits.

And even if you had a good reason to do that, why do it with a module? Why register your class instance in sys.modules? I think making things appear what they aren't is frowned upon in python.

Unless you are obfuscating code on purpose, I don't see why one would do all that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文