Encapsulation, inheritance and polymorphism
Dave Angel
d at davea.name
Wed Jul 18 18:33:01 CEST 2012
On 07/18/2012 08:58 AM, Steven D'Aprano wrote:
> <SNIP>
>
>
> 2) To check your internal reasoning in a function or method.
>
> For example:
>
> def foo(something):
> n = len(something)
> x = math.sqrt(x)
> # We expect that x must be less than half of n.
> # E.g. n=100 gives 10 < 50, which is correct.
> assert x < n//2
> process(n, x)
>
>
> <SNIP>
> For bonus points, can you see the mistake? The stated condition is wrong.
> Without the assert, the process() code could go off and potentially
> silently do the wrong thing, but the assert guards against that
> possibility. And once I've had a bug report that my app raises an
> AssertionError, I will go back and think more carefully about the
> assertion that sqrt(n) is always less than half of n.
>
>
There are actually two bugs in that function. One is in the assertion,
but more importantly, there's a typo earlier. One that would give a
traceback, so it would be caught quickly.
UnboundLocalError: local variable 'x' referenced before assignment
Once you change the argument of sqrt() to n, then you come to the
problem you were expecting; if n has a value of 1, 2, or 3, 4, or 5 the
assertion will fire.
--
DaveA
More information about the Python-list
mailing list