Optimizing methods away or not?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Dec 14 04:47:50 EST 2008


On Sun, 14 Dec 2008 09:19:45 +0000, Marc 'BlackJack' Rintsch wrote:

> On Sun, 14 Dec 2008 07:41:55 +0000, Steven D'Aprano wrote:
> 
>> I have a class with a method meant to verify internal program logic
>> (not data supplied by the caller). Because it is time-consuming but
>> optional, I treat it as a complex assertion statement, and optimize it
>> away if __debug__ is false:
...
>> What do others
>> think? Which do you consider better design?
> 
> None of it.  Why not simply:
> 
> class Parrot:
>     def __init__(self, *args):
>         print "Initialising instance..."
>         assert self._verify()
> 
>     def _verify(self):
>         print "Verifying..."
>         return None

For your method to work, I'd have to have _verify return a boolean flag 
instead of None, because assert None always fails.


> If you compile with -O the ``assert`` is optimized away.  But you still
> can call `_verify()` at specific points even in optimized code if you
> want or need.

That's a reasonable approach, if my use-case was for the caller to call 
the verify method. It's not: it's verifying my program logic rather than 
the caller's data, and it's only meaningful to do that verification at 
initialisation time.



-- 
Steven



More information about the Python-list mailing list