O'Reilly logo

NumPy Cookbook - Second Edition by Ivan Idris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Testing code with docstrings

Doctests are comment strings embedded in Python code that resemble interactive sessions. These strings can be used to test certain assumptions or just provide examples. We need to use the doctest module to run these tests.

Let's write a simple example that is supposed to calculate the factorial but doesn't cover all possible boundary conditions. In other words, some tests will fail.

How to do it...

  1. Write the docstring with a test that will pass and another test that will fail. The docstring text should look like what you would normally see in a Python shell:
    """
    Test for the factorial of 3 that should pass.
    >>> factorial(3)
    6
    
    Test for the factorial of 0 that should fail.
    >>> factorial(0)
    1
    """
    
  2. Write the following NumPy ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required