Python property gotcha

If you like using a single getter/setter function for your properties, watch out if using None for the default. If you do that you won't be able to set your property to None!

Example code and workaround...


class CantSetNone(object):
    def __init__(self):
        self._test = None

    def test(self, val=None):
        print "test(%s)" % `val`
        if val is None:
            return self._test
        else:
            self._test = val
    test = property(test, test)

class UNDEFINED:
    pass

class CanSetNone(object):
    def __init__(self):
        self._test = None

    def test(self, val=UNDEFINED):
        print "test(%s)" % `val`
        if val is UNDEFINED:
            return self._test
        else:
            self._test = val
    test = property(test, test)

Add new comment