Restricted attribute writing

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Aug 7 12:31:03 EDT 2011


Roy Smith wrote:

> In article <mailman.2010.1312731312.1164.python-list at python.org>,
>  John O'Hagan <research at johnohagan.com> wrote:
> 
>> I'm looking for good ways to ensure that attributes are only writable
>> such that they retain the characteristics the class requires.
> 
> Sounds like you're trying to do
> http://en.wikipedia.org/wiki/Design_by_contract.  Which is not a bad
> thing.  But, I think a more pythonic way to implement this would be to
> verify behaviors, not types.
> 
> I would start by writing a assert_invarient() method which validates the
> object.  I'm guessing all you really need is that you can index [0] and
> [1] and get ints, so test for that.  Something like:
> 
> def assert_invarient(self):
>    try:
>       assert isinstance(data[0], int)
>       assert isinstance(data[1], int)
>    except:
>       raise ValueError

Don't do that. assert is for testing program logic, not verifying data. The
problem with assert is that the user can turn all assertions off, simply by
launching Python with the -O switch. Your verification code then becomes:

def assert_invarient(self):
    try:
        pass
    except:
        raise ValueError

which is useless.

When should you use an assertion? If you've ever written code like this:

if condition:
    do_something()
else:
    # This should never happen. But you know what they say: code that 
    # can't happen, does!
    raise RuntimeError('condition unexpectedly false')


that's a prime candidate for turning into an assertion:


assert condition, 'condition unexpectedly false'
do_something()



-- 
Steven




More information about the Python-list mailing list