[英]magic imports in Python
编辑:我应该指定我(卡住)使用Python 2,但是有兴趣看看如何在2或3中解决这个问题
场景:我有一个名为shapes
的包。
我有一个模块shapes
称为factory
具有ShapeClassFactory
类。 这个类可以传递一个字符串,它将在远程数据库中查找数据并使用它来动态定义它返回的类。
shapes.py:
from .factory import ShapeClassFactory
__all__ = ['ShapeClassFactory']
实际上,这个包可以用在各种其他包和脚本中,如下所示:
from shapes import ShapeClassFactory
Circle = ShapeClassFactory("Circle")
Rect = ShapeClassFactory("Rect")
myCircle = Circle(r=5, fill='red')
mySquare = Rect(x=5, y=5, fill=None)
问题:以上都很好。 但是,我希望能够以这样的方式编写shapes
包,它可以像这样使用:
from shapes import Circle, Rect
myCircle = Circle(r=5, fill='red')
mySquare = Rect(x=5, y=5, fill=None)
...这个想法是,如果在shapes
找不到成员,它会使用ShapeClassFactory
来尝试生成它。
困难在于,在请求之前基本上不知道可用的类,因此预定义的类名列表将无济于事。
如果ShapeClassFactory
无法构建一个类,我不介意抛出一个ImportError
- 但是这样的事情甚至可能吗?
您可以通过在初始化时自动构造shapes
命名空间中的所有可能对象来完成此操作,只要没有太多可能的类并且预先初始化类的成本不是太大。 你可以在shapes.py中使用这样的代码:
from .factory import ShapeClassFactory
__all__ = ['ShapeClassFactory']
def get_shape_names():
"""Returns all valid shapes that can be passed in to ShapeClassFactory"""
return ['Circle', 'Rect'] # your own code should query the database
for name in get_shape_names():
globals()[name] = ShapeClassFactory(name)
__all__.append(name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.