在 Python 中自动加载 [英] Autoload in Python

查看:33
本文介绍了在 Python 中自动加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去,我使用 perl 的 AUTOLOAD 工具将符号延迟加载到命名空间中,并希望在 python 中具有相同的功能.

In the past I've used perl's AUTOLOAD facility for implementing lazy loading of symbols into a namespace, and wanted the same functionality in python.

传统上,您似乎最接近的是使用一个类和一个 __getattr__ 类来实现这种事情.但是我也尝试过在 sys.modules 中翻找,然后想出了这个:

Traditionally the closest you appear to be able to get is to use a class and a __getattr__ class to achieve this sort of thing. However I've also tried rummaging around in sys.modules, and come up with this:

# mymod.py
def greet(greeting="Hello World"):
   print greeting

class autoload(object):
    def __init__(self, __name__):
        super(autoload, self).__init__()
        self.wrapped_name = __name__
        self.wrapped = sys.modules[__name__]
    def __getattr__(self, name):
        try:
            return getattr(self.wrapped, name)
        except AttributeError:
            def f():
                greet(name+" "+self.wrapped_name)
            return f

if __name__ != "__main__":
    import sys
    sys.modules[__name__] = autoload(__name__)

从用户的角度来看,这确实按照我想要的方式工作:

This does work the way I'd like from a user perspective:

~> python
Python 2.5.1 (r251:54863, Jan 10 2008, 18:01:57)
[GCC 4.2.1 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymod
>>> mymod.hello()
hello
>>> from mymod import Hello_World
>>> Hello_World()
Hello_World

但它让我震惊 - 人们倾向于使用标准方法在 python 中自动加载吗?

But it strikes me - is there a standard approach that people tend to use for autoloading in python?

其次,对于有经验的 Python 开发人员来说,一个真正的问题是这对你来说是好的还是坏的做法"?我是一名经验丰富的 Python 开发人员,它让我觉得它真的很有用,但它让我觉得它处于边缘状态,并且对这是否可以被视为好的做法、不好的做法或类似做法很感兴趣.

Secondly, a question for experienced python developers really is "does this strike you as good or bad practice"? I'm a reasonably experienced python developer, and it strikes me as really useful, but it strikes me as borderline and interested in whether this can be viewed as good practice, bad practice or similar.

谢谢!

推荐答案

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

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

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

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.

回答延迟加载的问题:

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

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.

这篇关于在 Python 中自动加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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