Autoload in Python

给你一囗甜甜゛ 提交于 2019-11-28 04:34:56

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.

Alex Martelli

"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.

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.

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