如何对只读实例属性进行输入验证?

How to perform input validation for read-only instance attributes?

发布了一个非常相似的问题 here,但是没有公认的答案,没有代码示例,而且我真的不喜欢那里提供的唯一一个答案所建议的使用外部库的想法.

以下代码允许定义只读实例属性:

class Point:
    def __init__(self, x, y):
        self._x = x
        self._y = y

    @property
    def x(self):
        return self._x

    @property
    def y(self):
        return self._y

但我也想验证用户输入。我想验证 xy 的类型是否正确。

最 pythonic/elegant 的方法是什么?如果我提供设置器,属性将不再是只读的。

在构造函数中执行输入验证是唯一的方法吗?

这是一种优雅的 Pythonic 方式,它使用工厂函数来创建属性:

class ReadOnlyError(Exception):
    """Attempt made to assign a new value to something that can't be changed."""


# Based on recipe in book "Python Cookbook 3rd Edition" - section 9.21 -
# titled "Avoiding Repetitive Property Methods".
def readonly_typed_property(name, expected_type):
    storage_name = '_' + name

    @property
    def prop(self):
        return getattr(self, storage_name)

    @prop.setter
    def prop(self, value):
        if hasattr(self, storage_name):
            raise ReadOnlyError('{!r} is read-only!'.format(name))
        if not isinstance(value, expected_type):
            raise TypeError('{!r} must be a {!r}'.format(name, expected_type.__name__))
        setattr(self, storage_name, value)

    return prop


class Point:
    x = readonly_typed_property('x', int)
    y = readonly_typed_property('y', int)

    def __init__(self, x, y):
        self.x = x
        self.y = y


if __name__ == '__main__':
    try:
        p1 = Point(1, 2)
    except Exception as e:
        print('ERROR: No exception should have been raised for case 1.')
        print(e)
    else:
        print('As expected, NO exception raised for case 1.')

    print()
    try:
        p2 = Point('1', 2)
    except TypeError as e:
        print(e)
        print(f'As expected, {type(e).__name__} exception raised for case 2.')
    else:
        print('ERROR: expected TypeError exception not raised for case 2')

    print()
    try:
        p1.x = 42
    except Exception as e:
        print(e)
        print(f'As expected, {type(e).__name__} exception raised for case 3.')
    else:
        print('ERROR: expected ReadOnlyError exception not raised for case 3')