如何在Python中定义PyCharm友好的值对象?

Mic*_*kov 13 python pycharm

我很好奇在Python中定义值对象的好方法.每个维基百科:" 价值对象是一个小对象,代表一个简单的实体,其相等性不是基于身份:即当两个价值对象具有相同的价值时,它们是相同的,不一定是同一个对象".在Python中,本质上意味着重新定义__eq____hash__方法,以及不变性.

标准namedtuple似乎是几乎完美的解决方案,除了它们与PyCharm等现代Python IDE不能很好地兼容.我的意思是IDE不会真正提供有关定义为类的任何有用的见解namedtuple.虽然可以使用这样的技巧将docstring附加到这样的类:

class Point2D(namedtuple("Point2D", "x y")):
    """Class for immutable value objects"""
    pass
Run Code Online (Sandbox Code Playgroud)

根本没有地方可以对构造函数参数进行描述并指定它们的类型.PyCharm非常聪明,可以猜测Point2D"构造函数"的参数,但类型方面它是盲目的.

这段代码推入了一些类型信息,但它不是很有用:

class Point2D(namedtuple("Point2D", "x y")):
    """Class for immutable value objects"""
    def __new__(cls, x, y):
        """
        :param x: X coordinate
        :type x: float

        :param y: Y coordinate
        :type y: float

        :rtype: Point2D
        """
        return super(Point2D, cls).__new__(cls, x, y)

point = Point2D(1.0, 2.0)
Run Code Online (Sandbox Code Playgroud)

PyCharm在构造新对象时会看到类型,但是不会抓住那个点.x和point.y是浮点数,所以不会有助于检测它们的误用.而且我也不喜欢在常规基础上重新定义"魔法"方法的想法.

所以我正在寻找一些东西:

  • 就像普通的Python类或namedtuple一样容易定义
  • 提供价值语义(平等,散列,不变性)
  • 易于以一种可以与IDE很好地协作的方式进行记录

理想的解决方案可能如下所示:

class Point2D(ValueObject):
    """Class for immutable value objects"""
    def __init__(self, x, y):
        """
        :param x: X coordinate
        :type x: float

        :param y: Y coordinate
        :type y: float
        """
        super(Point2D, self).__init__(cls, x, y)
Run Code Online (Sandbox Code Playgroud)

或者那个:

class Point2D(object):
    """Class for immutable value objects"""

    __metaclass__ = ValueObject

    def __init__(self, x, y):
        """
        :param x: X coordinate
        :type x: float

        :param y: Y coordinate
        :type y: float
        """
        pass
Run Code Online (Sandbox Code Playgroud)

我试图找到这样的东西,但没有成功.我认为在我自己实施之前寻求帮助是明智的.

更新:在user4815162342的帮助下,我设法提出了一些有效的方法.这是代码:

class ValueObject(object):
    __slots__ = ()

    def __repr__(self):
        attrs = ' '.join('%s=%r' % (slot, getattr(self, slot)) for slot in self.__slots__)
        return '<%s %s>' % (type(self).__name__, attrs)

    def _vals(self):
        return tuple(getattr(self, slot) for slot in self.__slots__)

    def __eq__(self, other):
        if not isinstance(other, ValueObject):
            return NotImplemented
        return self.__slots__ == other.__slots__ and self._vals() == other._vals()

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(self._vals())

    def __getstate__(self):
        """
        Required to pickle classes with __slots__
        Must be consistent with __setstate__
        """
        return self._vals()

    def __setstate__(self, state):
        """
        Required to unpickle classes with __slots__
        Must be consistent with __getstate__
        """
        for slot, value in zip(self.__slots__, state):
            setattr(self, slot, value)
Run Code Online (Sandbox Code Playgroud)

它离理想的解决方案还很远.类声明如下所示:

class X(ValueObject):
    __slots__ = "a", "b", "c"

    def __init__(self, a, b, c):
        """
        :param a:
        :type a: int
        :param b:
        :type b: str
        :param c:
        :type c: unicode
        """
        self.a = a
        self.b = b
        self.c = c
Run Code Online (Sandbox Code Playgroud)

列出所有属性总共四次:in __slots__,in ctor arguments,docstring和ctor body.到目前为止,我不知道如何让它变得不那么尴尬.

Thi*_*anK 5

3.5 新版功能:typing模块和NamedTuple

在 3.5 版本中,typing添加了该模块,您将在其中找到一个完全符合您需求的类。

新的 NamedTuple

它的工作原理与您期望的一样:


注意
截至今天,该 API 仍处于临时阶段。这意味着在发布新版本时不能保证向后兼容。界面不会发生变化。我个人的看法是:考虑到设计的简单性,如果有变化,我相信这将是一个简单的重构;)


use*_*342 4

您的要求虽然表达得很仔细,但我不太清楚,部分原因是我不使用 PyCharm GUI。但这里有一个尝试:

class ValueObject(object):
    __slots__ = ()

    def __init__(self, *vals):
        if len(vals) != len(self.__slots__):
            raise TypeError, "%s.__init__ accepts %d arguments, got %d" \
                % (type(self).__name__, len(self.__slots__), len(vals))
        for slot, val in zip(self.__slots__, vals):
            super(ValueObject, self).__setattr__(slot, val)

    def __repr__(self):
        return ('<%s[0x%x] %s>'
                % (type(self).__name__, id(self),
                   ' '.join('%s=%r' % (slot, getattr(self, slot))
                            for slot in self.__slots__)))

    def _vals(self):
        return tuple(getattr(self, slot) for slot in self.__slots__)

    def __eq__(self, other):
        if not isinstance(other, ValueObject):
            return NotImplemented
        return self.__slots__ == other.__slots__ and self._vals() == other._vals()

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(self._vals())

    def __setattr__(self, attr, val):
        if attr in self.__slots__:
            raise AttributeError, "%s slot '%s' is read-only" % (type(self).__name__, attr)
        super(ValueObject, self).__setattr__(attr, val)
Run Code Online (Sandbox Code Playgroud)

用法是这样的:

class X(ValueObject):
  __slots__ = 'a', 'b'
Run Code Online (Sandbox Code Playgroud)

这将为您提供一个具体的值类,其中包含两个只读槽和一个自动生成的构造函数 、__eq____hash__。例如:

>>> x = X(1.0, 2.0, 3.0)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 5, in __init__
TypeError: X.__init__ accepts 2 arguments, got 3
>>> x = X(1.0, 2.0)
>>> x
<X[0x4440a50] a=1.0 b=2.0>
>>> x.a
1.0
>>> x.b
2.0
>>> x.a = 10
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 32, in __setattr__
AttributeError: X slot 'a' is read-only
>>> x.c = 10
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 33, in __setattr__
AttributeError: 'X' object has no attribute 'c'
>>> dir(x)
['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_vals', 'a', 'b']
>>> x == X(1.0, 2.0)
True
>>> x == X(1.0, 3.0)
False
>>> hash(x)
3713081631934410656
>>> hash(X(1.0, 2.0))
3713081631934410656
>>> hash(X(1.0, 3.0))
3713081631933328131
Run Code Online (Sandbox Code Playgroud)

如果需要,您可以使用文档字符串定义您自己的__init__文档字符串(大概)为您的 IDE 提供类型注释提示。