在过去,我已经使用perl的AUTOLOAD工具来实现将懒惰的符号加载到命名空间中,并且希望在python中具有相同的功能.
传统上,你看起来最接近的是使用一个类和一个__getattr__类来实现这种事情.不过,我也试过在sys.modules中进行翻录,并提出了这一点:
- # mymod.py
- def greet(greeting="Hello World"):
- print greeting
- class AutoLoad(object):
- def __init__(self,mod_name):
- super(autoload,self).__init__()
- self.wrapped_name = mod_name
- self.wrapped = sys.modules[mod_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__)
从用户的角度来看,这样做是有用的:
- ~> 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 mymod
- >>> from mymod import Hello_World
- >>> Hello_World()
- Hello_World mymod
但是它打击了我 – 有人用一个标准的方法来自动加载python?
其次,有经验的python开发人员的问题是“这样做你是好还是坏的做法”?我是一个经验丰富的python开发人员,它对我来说真的很有用,但它使我成为一个边界,感兴趣的是这可以被看作是好的做法,不好的做法或类似的.
解决方法
“懒惰进口”可以建立在
PEP 302年规定的“新进口钩”之上,现已全面实施. PEP 369用于涵盖“懒惰进口”以及进口后钩,但之后被简化,现在只包括进口后挂钩;还是你可能对
original draft感兴趣.
可以在this recipe中找到通过Meta_path钩子实现“懒惰导入”的好方法.