[英]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.