index.html 30 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="last-modified" content="2017-08-04 00:20:27 +0200">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- meta "search-domain" used for google site search function google_search() -->
    <meta name="search-domain" value="/swc-releases/2017.08/python-novice-inflammation">
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="../assets/css/lesson.css" />
    
    <link rel="shortcut icon" type="image/x-icon" href="/favicon-swc.ico" />
    
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
	<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
	<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
	<![endif]-->
    <title>Programming with Python: Defensive Programming</title>
  </head>
  <body>
    <div class="container">
      
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>

      
      

      
      <a class="navbar-brand" href="../">Home</a>

    </div>
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">

	
        <li><a href="../conduct/">Code of Conduct</a></li>

	
        
        <li><a href="../setup/">Setup</a></li>
        <li class="dropdown">
          <a href="../" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Episodes <span class="caret"></span></a>
          <ul class="dropdown-menu">
            
            <li><a href="../01-numpy/">Analyzing Patient Data</a></li>
            
            <li><a href="../02-loop/">Repeating Actions with Loops</a></li>
            
            <li><a href="../03-lists/">Storing Multiple Values in Lists</a></li>
            
            <li><a href="../04-files/">Analyzing Data from Multiple Files</a></li>
            
            <li><a href="../05-cond/">Making Choices</a></li>
            
            <li><a href="../06-func/">Creating Functions</a></li>
            
            <li><a href="../07-errors/">Errors and Exceptions</a></li>
            
            <li><a href="../08-defensive/">Defensive Programming</a></li>
            
            <li><a href="../09-debugging/">Debugging</a></li>
            
            <li><a href="../10-cmdline/">Command-Line Programs</a></li>
            
	    <li role="separator" class="divider"></li>
            <li><a href="../aio/">All in one page (Beta)</a></li>
          </ul>
        </li>
	

	
	
        <li class="dropdown">
          <a href="../" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Extras <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="../reference/">Reference</a></li>
            
            <li><a href="../about/">About</a></li>
            
            <li><a href="../discuss/">Discussion</a></li>
            
            <li><a href="../figures/">Figures</a></li>
            
            <li><a href="../guide/">Instructor Notes</a></li>
            
          </ul>
        </li>
	

	
        <li><a href="../license/">License</a></li>
	
	<li><a href="/edit/gh-pages/_episodes/08-defensive.md">Improve this page <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a></li>
	
      </ul>
      <form class="navbar-form navbar-right" role="search" id="search" onsubmit="google_search(); return false;">
        <div class="form-group">
          <input type="text" id="google-search" placeholder="Search..." aria-label="Google site search">
        </div>
      </form>
    </div>
  </div>
</nav>


<div class="row">
  <div class="col-md-1">
    <h3>
      
      <a href="../07-errors/"><span class="glyphicon glyphicon-menu-left" aria-hidden="true"></span><span class="sr-only">previous episode</span></a>
      
    </h3>
  </div>
  <div class="col-md-10">
    
    <h3 class="maintitle"><a href="../">Programming with Python</a></h3>
    
  </div>
  <div class="col-md-1">
    <h3>
      
      <a href="../09-debugging/"><span class="glyphicon glyphicon-menu-right" aria-hidden="true"></span><span class="sr-only">next episode</span></a>
      
    </h3>
  </div>
</div>

<article>
<div class="row">
  <div class="col-md-1">
  </div>
  <div class="col-md-10">
    <h1 class="maintitle">Defensive Programming</h1>
  </div>
  <div class="col-md-1">
  </div>
</div>


<blockquote class="objectives">
  <h2>Overview</h2>

  <div class="row">
    <div class="col-md-3">
      <strong>Teaching:</strong> 30 min
      <br/>
      <strong>Exercises:</strong> 0 min
    </div>
    <div class="col-md-9">
      <strong>Questions</strong>
      <ul>
	
	<li><p>How can I make my programs more reliable?</p>
</li>
	
      </ul>
    </div>
  </div>

  <div class="row">
    <div class="col-md-3">
    </div>
    <div class="col-md-9">
      <strong>Objectives</strong>
      <ul>
	
	<li><p>Explain what an assertion is.</p>
</li>
	
	<li><p>Add assertions that check the program’s state is correct.</p>
</li>
	
	<li><p>Correctly add precondition and postcondition assertions to functions.</p>
</li>
	
	<li><p>Explain what test-driven development is, and use it when creating new functions.</p>
</li>
	
	<li><p>Explain why variables should be initialized using actual data values rather than arbitrary constants.</p>
</li>
	
      </ul>
    </div>
  </div>

</blockquote>

<p>Our previous lessons have introduced the basic tools of programming:
variables and lists,
file I/O,
loops,
conditionals,
and functions.
What they <em>haven’t</em> done is show us how to tell
whether a program is getting the right answer,
and how to tell if it’s <em>still</em> getting the right answer
as we make changes to it.</p>

<p>To achieve that,
we need to:</p>

<ul>
  <li>Write programs that check their own operation.</li>
  <li>Write and run tests for widely-used functions.</li>
  <li>Make sure we know what “correct” actually means.</li>
</ul>

<p>The good news is,
doing these things will speed up our programming,
not slow it down.
As in real carpentry — the kind done with lumber — the time saved
by measuring carefully before cutting a piece of wood
is much greater than the time that measuring takes.</p>

<h2 id="assertions">Assertions</h2>

<p>The first step toward getting the right answers from our programs
is to assume that mistakes <em>will</em> happen
and to guard against them.
This is called <a href="../reference/#defensive-programming">defensive programming</a>,
and the most common way to do it is to add <a href="../reference/#assertion">assertions</a> to our code
so that it checks itself as it runs.
An assertion is simply a statement that something must be true at a certain point in a program.
When Python sees one,
it evaluates the assertion’s condition.
If it’s true,
Python does nothing,
but if it’s false,
Python halts the program immediately
and prints the error message if one is provided.
For example,
this piece of code halts as soon as the loop encounters a value that isn’t positive:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>numbers = [1.5, 2.3, 0.7, -0.001, 4.4]
total = 0.0
for n in numbers:
    assert n &gt; 0.0, 'Data should only contain positive values'
    total += n
print('total is:', total)
</code></pre>
</div>

<div class="error highlighter-rouge"><pre class="highlight"><code>---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
&lt;ipython-input-19-33d87ea29ae4&gt; in &lt;module&gt;()
      2 total = 0.0
      3 for n in numbers:
----&gt; 4     assert n &gt; 0.0, 'Data should only contain positive values'
      5     total += n
      6 print('total is:', total)

AssertionError: Data should only contain positive values
</code></pre>
</div>

<p>Programs like the Firefox browser are full of assertions:
10-20% of the code they contain
are there to check that the other 80-90% are working correctly.
Broadly speaking,
assertions fall into three categories:</p>

<ul>
  <li>
    <p>A <a href="../reference/#precondition">precondition</a> is something that must be true at the start of a function in order for it to work correctly.</p>
  </li>
  <li>
    <p>A <a href="../reference/#postcondition">postcondition</a> is something that the function guarantees is true when it finishes.</p>
  </li>
  <li>
    <p>An <a href="../reference/#invariant">invariant</a> is something that is always true at a particular point inside a piece of code.</p>
  </li>
</ul>

<p>For example,
suppose we are representing rectangles using a <a href="../reference/#tuple">tuple</a> of four coordinates <code class="highlighter-rouge">(x0, y0, x1, y1)</code>,
representing the lower left and upper right corners of the rectangle.
In order to do some calculations,
we need to normalize the rectangle so that the lower left corner is at the origin
and the longest side is 1.0 units long.
This function does that,
but checks that its input is correctly formatted and that its result makes sense:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>def normalize_rectangle(rect):
    '''Normalizes a rectangle so that it is at the origin and 1.0 units long on its longest axis.'''
    assert len(rect) == 4, 'Rectangles must contain 4 coordinates'
    x0, y0, x1, y1 = rect
    assert x0 &lt; x1, 'Invalid X coordinates'
    assert y0 &lt; y1, 'Invalid Y coordinates'

    dx = x1 - x0
    dy = y1 - y0
    if dx &gt; dy:
        scaled = float(dx) / dy
        upper_x, upper_y = 1.0, scaled
    else:
        scaled = float(dx) / dy
        upper_x, upper_y = scaled, 1.0

    assert 0 &lt; upper_x &lt;= 1.0, 'Calculated upper X coordinate invalid'
    assert 0 &lt; upper_y &lt;= 1.0, 'Calculated upper Y coordinate invalid'

    return (0, 0, upper_x, upper_y)
</code></pre>
</div>

<p>The preconditions on lines 3, 5, and 6 catch invalid inputs:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print(normalize_rectangle( (0.0, 1.0, 2.0) )) # missing the fourth coordinate
</code></pre>
</div>

<div class="error highlighter-rouge"><pre class="highlight"><code>---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
&lt;ipython-input-21-3a97b1dcab70&gt; in &lt;module&gt;()
----&gt; 1 print(normalize_rectangle( (0.0, 1.0, 2.0) )) # missing the fourth coordinate

&lt;ipython-input-20-408dc39f3915&gt; in normalize_rectangle(rect)
      1 def normalize_rectangle(rect):
      2     '''Normalizes a rectangle so that it is at the origin and 1.0 units long on its longest axis.'''
----&gt; 3     assert len(rect) == 4, 'Rectangles must contain 4 coordinates'
      4     x0, y0, x1, y1 = rect
      5     assert x0 &lt; x1, 'Invalid X coordinates'

AssertionError: Rectangles must contain 4 coordinates
</code></pre>
</div>

<div class="python highlighter-rouge"><pre class="highlight"><code>print(normalize_rectangle( (4.0, 2.0, 1.0, 5.0) )) # X axis inverted
</code></pre>
</div>

<div class="error highlighter-rouge"><pre class="highlight"><code>---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
&lt;ipython-input-22-f05ae7878a45&gt; in &lt;module&gt;()
----&gt; 1 print(normalize_rectangle( (4.0, 2.0, 1.0, 5.0) )) # X axis inverted

&lt;ipython-input-20-408dc39f3915&gt; in normalize_rectangle(rect)
      3     assert len(rect) == 4, 'Rectangles must contain 4 coordinates'
      4     x0, y0, x1, y1 = rect
----&gt; 5     assert x0 &lt; x1, 'Invalid X coordinates'
      6     assert y0 &lt; y1, 'Invalid Y coordinates'
      7

AssertionError: Invalid X coordinates
</code></pre>
</div>

<p>The post-conditions on lines 17 and 18 help us catch bugs by telling us when our calculations cannot have been correct.
For example,
if we normalize a rectangle that is taller than it is wide everything seems OK:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print(normalize_rectangle( (0.0, 0.0, 1.0, 5.0) ))
</code></pre>
</div>

<div class="output highlighter-rouge"><pre class="highlight"><code>(0, 0, 0.2, 1.0)
</code></pre>
</div>

<p>but if we normalize one that’s wider than it is tall,
the assertion is triggered:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>print(normalize_rectangle( (0.0, 0.0, 5.0, 1.0) ))
</code></pre>
</div>

<div class="error highlighter-rouge"><pre class="highlight"><code>---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
&lt;ipython-input-24-5f0ef7954aeb&gt; in &lt;module&gt;()
----&gt; 1 print(normalize_rectangle( (0.0, 0.0, 5.0, 1.0) ))

&lt;ipython-input-20-408dc39f3915&gt; in normalize_rectangle(rect)
     16
     17     assert 0 &lt; upper_x &lt;= 1.0, 'Calculated upper X coordinate invalid'
---&gt; 18     assert 0 &lt; upper_y &lt;= 1.0, 'Calculated upper Y coordinate invalid'
     19
     20     return (0, 0, upper_x, upper_y)

AssertionError: Calculated upper Y coordinate invalid
</code></pre>
</div>

<p>Re-reading our function,
we realize that line 11 should divide <code class="highlighter-rouge">dy</code> by <code class="highlighter-rouge">dx</code> rather than <code class="highlighter-rouge">dx</code> by <code class="highlighter-rouge">dy</code>.
(You can display line numbers by typing Ctrl-M, then L.)
If we had left out the assertion at the end of the function,
we would have created and returned something that had the right shape as a valid answer,
but wasn’t.
Detecting and debugging that would almost certainly have taken more time in the long run
than writing the assertion.</p>

<p>But assertions aren’t just about catching errors:
they also help people understand programs.
Each assertion gives the person reading the program
a chance to check (consciously or otherwise)
that their understanding matches what the code is doing.</p>

<p>Most good programmers follow two rules when adding assertions to their code.
The first is, <em>fail early, fail often</em>.
The greater the distance between when and where an error occurs and when it’s noticed,
the harder the error will be to debug,
so good code catches mistakes as early as possible.</p>

<p>The second rule is, <em>turn bugs into assertions or tests</em>.
Whenever you fix a bug, write an assertion that catches the mistake
should you make it again.
If you made a mistake in a piece of code,
the odds are good that you have made other mistakes nearby,
or will make the same mistake (or a related one)
the next time you change it.
Writing assertions to check that you haven’t <a href="../reference/#regression">regressed</a>
(i.e., haven’t re-introduced an old problem)
can save a lot of time in the long run,
and helps to warn people who are reading the code
(including your future self)
that this bit is tricky.</p>

<h2 id="test-driven-development">Test-Driven Development</h2>

<p>An assertion checks that something is true at a particular point in the program.
The next step is to check the overall behavior of a piece of code,
i.e.,
to make sure that it produces the right output when it’s given a particular input.
For example,
suppose we need to find where two or more time series overlap.
The range of each time series is represented as a pair of numbers,
which are the time the interval started and ended.
The output is the largest range that they all include:</p>

<p><img src="../fig/python-overlapping-ranges.svg" alt="Overlapping Ranges" /></p>

<p>Most novice programmers would solve this problem like this:</p>

<ol>
  <li>Write a function <code class="highlighter-rouge">range_overlap</code>.</li>
  <li>Call it interactively on two or three different inputs.</li>
  <li>If it produces the wrong answer, fix the function and re-run that test.</li>
</ol>

<p>This clearly works — after all, thousands of scientists are doing it right now — but
there’s a better way:</p>

<ol>
  <li>Write a short function for each test.</li>
  <li>Write a <code class="highlighter-rouge">range_overlap</code> function that should pass those tests.</li>
  <li>If <code class="highlighter-rouge">range_overlap</code> produces any wrong answers, fix it and re-run the test functions.</li>
</ol>

<p>Writing the tests <em>before</em> writing the function they exercise
is called <a href="../reference/#test-driven-development">test-driven development</a> (TDD).
Its advocates believe it produces better code faster because:</p>

<ol>
  <li>If people write tests after writing the thing to be tested,
they are subject to confirmation bias,
i.e.,
they subconsciously write tests to show that their code is correct,
rather than to find errors.</li>
  <li>Writing tests helps programmers figure out what the function is actually supposed to do.</li>
</ol>

<p>Here are three test functions for <code class="highlighter-rouge">range_overlap</code>:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>assert range_overlap([ (0.0, 1.0) ]) == (0.0, 1.0)
assert range_overlap([ (2.0, 3.0), (2.0, 4.0) ]) == (2.0, 3.0)
assert range_overlap([ (0.0, 1.0), (0.0, 2.0), (-1.0, 1.0) ]) == (0.0, 1.0)
</code></pre>
</div>

<div class="error highlighter-rouge"><pre class="highlight"><code>---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
&lt;ipython-input-25-d8be150fbef6&gt; in &lt;module&gt;()
----&gt; 1 assert range_overlap([ (0.0, 1.0) ]) == (0.0, 1.0)
      2 assert range_overlap([ (2.0, 3.0), (2.0, 4.0) ]) == (2.0, 3.0)
      3 assert range_overlap([ (0.0, 1.0), (0.0, 2.0), (-1.0, 1.0) ]) == (0.0, 1.0)

AssertionError:
</code></pre>
</div>

<p>The error is actually reassuring:
we haven’t written <code class="highlighter-rouge">range_overlap</code> yet,
so if the tests passed,
it would be a sign that someone else had
and that we were accidentally using their function.</p>

<p>And as a bonus of writing these tests,
we’ve implicitly defined what our input and output look like:
we expect a list of pairs as input,
and produce a single pair as output.</p>

<p>Something important is missing, though.
We don’t have any tests for the case where the ranges don’t overlap at all:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>assert range_overlap([ (0.0, 1.0), (5.0, 6.0) ]) == ???
</code></pre>
</div>

<p>What should <code class="highlighter-rouge">range_overlap</code> do in this case:
fail with an error message,
produce a special value like <code class="highlighter-rouge">(0.0, 0.0)</code> to signal that there’s no overlap,
or something else?
Any actual implementation of the function will do one of these things;
writing the tests first helps us figure out which is best
<em>before</em> we’re emotionally invested in whatever we happened to write
before we realized there was an issue.</p>

<p>And what about this case?</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>assert range_overlap([ (0.0, 1.0), (1.0, 2.0) ]) == ???
</code></pre>
</div>

<p>Do two segments that touch at their endpoints overlap or not?
Mathematicians usually say “yes”,
but engineers usually say “no”.
The best answer is “whatever is most useful in the rest of our program”,
but again,
any actual implementation of <code class="highlighter-rouge">range_overlap</code> is going to do <em>something</em>,
and whatever it is ought to be consistent with what it does when there’s no overlap at all.</p>

<p>Since we’re planning to use the range this function returns
as the X axis in a time series chart,
we decide that:</p>

<ol>
  <li>every overlap has to have non-zero width, and</li>
  <li>we will return the special value <code class="highlighter-rouge">None</code> when there’s no overlap.</li>
</ol>

<p><code class="highlighter-rouge">None</code> is built into Python,
and means “nothing here”.
(Other languages often call the equivalent value <code class="highlighter-rouge">null</code> or <code class="highlighter-rouge">nil</code>).
With that decision made,
we can finish writing our last two tests:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>assert range_overlap([ (0.0, 1.0), (5.0, 6.0) ]) == None
assert range_overlap([ (0.0, 1.0), (1.0, 2.0) ]) == None
</code></pre>
</div>

<div class="error highlighter-rouge"><pre class="highlight"><code>---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
&lt;ipython-input-26-d877ef460ba2&gt; in &lt;module&gt;()
----&gt; 1 assert range_overlap([ (0.0, 1.0), (5.0, 6.0) ]) == None
      2 assert range_overlap([ (0.0, 1.0), (1.0, 2.0) ]) == None

AssertionError:
</code></pre>
</div>

<p>Again,
we get an error because we haven’t written our function,
but we’re now ready to do so:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>def range_overlap(ranges):
    '''Return common overlap among a set of [low, high] ranges.'''
    lowest = 0.0
    highest = 1.0
    for (low, high) in ranges:
        lowest = max(lowest, low)
        highest = min(highest, high)
    return (lowest, highest)
</code></pre>
</div>

<p>(Take a moment to think about why we use <code class="highlighter-rouge">max</code> to raise <code class="highlighter-rouge">lowest</code>
and <code class="highlighter-rouge">min</code> to lower <code class="highlighter-rouge">highest</code>).
We’d now like to re-run our tests,
but they’re scattered across three different cells.
To make running them easier,
let’s put them all in a function:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>def test_range_overlap():
    assert range_overlap([ (0.0, 1.0), (5.0, 6.0) ]) == None
    assert range_overlap([ (0.0, 1.0), (1.0, 2.0) ]) == None
    assert range_overlap([ (0.0, 1.0) ]) == (0.0, 1.0)
    assert range_overlap([ (2.0, 3.0), (2.0, 4.0) ]) == (2.0, 3.0)
    assert range_overlap([ (0.0, 1.0), (0.0, 2.0), (-1.0, 1.0) ]) == (0.0, 1.0)
</code></pre>
</div>

<p>We can now test <code class="highlighter-rouge">range_overlap</code> with a single function call:</p>

<div class="python highlighter-rouge"><pre class="highlight"><code>test_range_overlap()
</code></pre>
</div>

<div class="error highlighter-rouge"><pre class="highlight"><code>---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
&lt;ipython-input-29-cf9215c96457&gt; in &lt;module&gt;()
----&gt; 1 test_range_overlap()

&lt;ipython-input-28-5d4cd6fd41d9&gt; in test_range_overlap()
      1 def test_range_overlap():
----&gt; 2     assert range_overlap([ (0.0, 1.0), (5.0, 6.0) ]) == None
      3     assert range_overlap([ (0.0, 1.0), (1.0, 2.0) ]) == None
      4     assert range_overlap([ (0.0, 1.0) ]) == (0.0, 1.0)
      5     assert range_overlap([ (2.0, 3.0), (2.0, 4.0) ]) == (2.0, 3.0)

AssertionError:
</code></pre>
</div>

<p>The first test that was supposed to produce <code class="highlighter-rouge">None</code> fails,
so we know something is wrong with our function.
We <em>don’t</em> know whether the other tests passed or failed
because Python halted the program as soon as it spotted the first error.
Still,
some information is better than none,
and if we trace the behavior of the function with that input,
we realize that we’re initializing <code class="highlighter-rouge">lowest</code> and <code class="highlighter-rouge">highest</code> to 0.0 and 1.0 respectively,
regardless of the input values.
This violates another important rule of programming:
<em>always initialize from data</em>.</p>

<blockquote class="challenge">
  <h2 id="pre--and-post-conditions">Pre- and Post-Conditions</h2>

  <p>Suppose you are writing a function called <code class="highlighter-rouge">average</code> that calculates the average of the numbers in a list.
What pre-conditions and post-conditions would you write for it?
Compare your answer to your neighbor’s:
can you think of a function that will pass your tests but not his/hers or vice versa?</p>

  <blockquote class="solution">
    <h2 id="solution">Solution</h2>
    <div class="python highlighter-rouge"><pre class="highlight"><code># a possible pre-condition:
assert len(input_list) &gt; 0, 'List length must be non-zero'
# a possible post-condition:
assert numpy.min(input_list) &lt;= average &lt;= numpy.max(input_list), 'Average should be between min and max of input values (inclusive)'
</code></pre>
    </div>
  </blockquote>
</blockquote>

<blockquote class="challenge">
  <h2 id="testing-assertions">Testing Assertions</h2>

  <p>Given a sequence of a number of cars, the function <code class="highlighter-rouge">get_total_cars</code> returns
the total number of cars.</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>get_total_cars([1, 2, 3, 4])
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>10
</code></pre>
  </div>

  <div class="python highlighter-rouge"><pre class="highlight"><code>get_total_cars(['a', 'b', 'c'])
</code></pre>
  </div>

  <div class="output highlighter-rouge"><pre class="highlight"><code>ValueError: invalid literal for int() with base 10: 'a'
</code></pre>
  </div>

  <p>Explain in words what the assertions in this function check,
and for each one,
give an example of input that will make that assertion fail.</p>

  <div class="python highlighter-rouge"><pre class="highlight"><code>def get_total(values):
    assert len(values) &gt; 0
    for element in values:
    	assert int(element)
    values = [int(element) for element in values]
    total = sum(values)
    assert total &gt; 0
    return total
</code></pre>
  </div>

  <blockquote class="solution">
    <h2 id="solution-1">Solution</h2>
    <ul>
      <li>The first assertion checks that the input sequence <code class="highlighter-rouge">values</code> is not empty.
An empty sequence such as <code class="highlighter-rouge">[]</code> will make it fail.</li>
      <li>The second assertion checks that each value in the list can be turned into an integer.
Input such as <code class="highlighter-rouge">[1, 2,'c', 3]</code> will make it fail.</li>
      <li>The third assertion checks that the total of the list is greater than 0.
Input such as <code class="highlighter-rouge">[-10, 2, 3]</code> will make it fail.</li>
    </ul>
  </blockquote>
</blockquote>

<blockquote class="challenge">
  <h2 id="fixing-and-testing">Fixing and Testing</h2>

  <p>Fix <code class="highlighter-rouge">range_overlap</code>. Re-run <code class="highlighter-rouge">test_range_overlap</code> after each change you make.</p>

  <blockquote class="solution">
    <h2 id="solution-2">Solution</h2>
    <div class="python highlighter-rouge"><pre class="highlight"><code>import numpy

def range_overlap(ranges):
    '''Return common overlap among a set of [low, high] ranges.'''
    if not ranges:
        # ranges is None or an empty list
        return None
    lowest, highest = ranges[0]
    for (low, high) in ranges[1:]:
        lowest = max(lowest, low)
        highest = min(highest, high)
    if lowest &gt;= highest:  # no overlap
        return None
    else:
        return (lowest, highest)
</code></pre>
    </div>
  </blockquote>
</blockquote>


<blockquote class="keypoints">
  <h2>Key Points</h2>
  <ul>
    
    <li><p>Program defensively, i.e., assume that errors are going to arise, and write code to detect them when they do.</p>
</li>
    
    <li><p>Put assertions in programs to check their state as they run, and to help readers understand how those programs are supposed to work.</p>
</li>
    
    <li><p>Use preconditions to check that the inputs to a function are safe to use.</p>
</li>
    
    <li><p>Use postconditions to check that the output from a function is safe to use.</p>
</li>
    
    <li><p>Write tests before writing code in order to help determine exactly what that code is supposed to do.</p>
</li>
    
  </ul>
</blockquote>

</article>

<div class="row">
  <div class="col-md-1">
    <h3>
      
      <a href="../07-errors/"><span class="glyphicon glyphicon-menu-left" aria-hidden="true"></span><span class="sr-only">previous episode</span></a>
      
    </h3>
  </div>
  <div class="col-md-10">
    
  </div>
  <div class="col-md-1">
    <h3>
      
      <a href="../09-debugging/"><span class="glyphicon glyphicon-menu-right" aria-hidden="true"></span><span class="sr-only">next episode</span></a>
      
    </h3>
  </div>
</div>


      
      
<footer>
  <div class="row">
    <div class="col-md-6" align="left">
      <h4>
	Copyright &copy; 2016–2017
	
	<a href="https://software-carpentry.org">Software Carpentry Foundation</a>
	
      </h4>
    </div>
    <div class="col-md-6" align="right">
      <h4>
	
	<a href="/edit/gh-pages/_episodes/08-defensive.md">Edit on GitHub</a>
	
	/
	<a href="/blob/gh-pages/CONTRIBUTING.md">Contributing</a>
	/
	<a href="/">Source</a>
	/
	<a href="/blob/gh-pages/CITATION">Cite</a>
	/
	<a href="">Contact</a>
      </h4>
    </div>
  </div>
</footer>

      
    </div>
    
<script src="../assets/js/jquery.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/lesson.js"></script>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-37305346-2', 'auto');
  ga('send', 'pageview');
</script>

  </body>
</html>