开发者

Python assert on property set

Is it possible to make a property assert when it is changed (for the purpose of debugging)?

class MyClass(object):
    def set_my_property(self, value):
        self.my_property = value
        # TODO: mark my_property so that if it gets set again, an assert
        # is trigger开发者_StackOverflow中文版ed

c = MyClass()
c.set_my_property(4)

# any of these lines would cause an assertion
c.set_my_property(8)
c.my_property = 123


EDIT: Is this what you're looking for?

class MyClass(object):
    def __init__(self):
        self.trigger = False
        self._my_property = 0

    def set_my_property(self, value):
        if self.trigger:
            raise Exception("WHOOPS!")
        self._my_property = value
        # TODO: mark my_property so that if it gets set again, an assert
        # is triggered
        self.trigger = True

    def get_my_property(self):
        return self._my_property

    my_property = property(get_my_property, set_my_property, None)

c = MyClass()
c.set_my_property(4)

# any of these lines would cause an assertion
c.set_my_property(8)
c.my_property = 123


Add a boolean to check if the value has been set before:

EDIT: But you want a property, so you'll need to create one:

class MyClass(object):
    def __init__(self):
        self.my_property_set = False
        self._my_property = None

    def set_my_property(self, value):
        self._my_property = value
        assert not self.my_property_set,"my_property already set"
        self.my_property_set = True

    def get_my_property(self):
        return self._my_property

    my_property = property(get_my_property, set_my_property, None)

c = MyClass()
c.set_my_property(4)

# any of these lines would cause an assertion
c.set_my_property(8)
c.my_property = 123


class Foo:
    def __init__(self):
        self._bar = None

    @property
    def bar(self): return self._bar

    @bar.setter:
    def bar(self, value):
        assert value != some_constant # your assert condition
        self._bar = value

    @bar.deleter:
    def bar(self, value):
        assert value != some_constant # your assert condition
        self._bar = None
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜