Esc*_*alo 13 python architecture metaclass backend linear-algebra
我正在用Python原型化一个新系统; 功能主要是数字.
一个重要的要求是能够使用不同的线性代数后端:从单个用户实现到通用库,如Numpy.线性代数实现(即后端)必须独立于接口.
我最初的架构尝试如下:
>>> v1 = Vector([1,2,3])
>>> v2 = Vector([4,5,6])
>>> print v1 * v2
>>> # prints "Vector([4, 10, 18])"
Run Code Online (Sandbox Code Playgroud)
# this example uses numpy as the back-end, but I mean
# to do this for a general back-end
import numpy
def numpy_array(*args): # creates a numpy array from the arguments
return numpy.array(*args)
class VectorBase(type):
def __init__(cls, name, bases, attrs):
engine = attrs.pop("engine", None)
if not engine:
raise RuntimeError("you need to specify an engine")
# this implementation would change depending on `engine`
def new(cls, *args):
return numpy_array(*args)
setattr(cls, "new", classmethod(new))
class Vector(object):
__metaclass__ = VectorBase
# I could change this at run time
# and offer alternative back-ends
engine = "numpy"
@classmethod
def create(cls, v):
nv = cls()
nv._v = v
return nv
def __init__(self, *args):
self._v = None
if args:
self._v = self.new(*args)
def __repr__(self):
l = [item for item in self._v]
return "Vector(%s)" % repr(l)
def __mul__(self, other):
try:
return Vector.create(self._v * other._v)
except AttributeError:
return Vector.create(self._v * other)
def __rmul__(self, other):
return self.__mul__(other)
Run Code Online (Sandbox Code Playgroud)
这个简单的例子如下工作:Vector该类保留对后端(numpy.ndarray在示例中)所做的向量实例的引用; 所有算术调用都由接口实现,但是它们的评估被推迟到后端.
在实践中,接口会重载所有适当的操作符并延迟到后端(示例仅显示__mul__和__rmul__,但您可以遵循相同的操作).
我愿意放弃一些性能来换取可定制性.即使在我的示例有效的情况下,它也感觉不对 - 我会用很多构造函数调用来削弱后端!这需要不同的metaclass实现,允许更好的呼叫延迟.
那么,您如何推荐我实现此功能?我需要强调保持所有系统Vector实例均匀且独立于线性代数后端的重要性.
| 归档时间: |
|
| 查看次数: |
568 次 |
| 最近记录: |