
Tips & Tricks
csmatrix.org
You can use csmatrix.org to access the course page (http://cs.brown.edu/courses/cs053/current/index.htm)
python3 -i <your script>
python3 -i <your script> runs the script in the interactive mode: after the script finishes, instead of exiting the Python execution and returning the control to shell, Python will enter the REPL mode. The top-level declarations will be available so that you can interact with. This is extremely useful for debugging.
Example:
$ cat test.py def square(x): return x*x value = [square(x) for x in range(10)] $ python3 -i test.py # this runs the script and then enters the REPL mode >>> value # you can interact with values defined in the script [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> sum(value) 285 >>> square(sum(value)) # you can use functions defined in the script 81225 >>> 285**2 81225 >>> quit() $ _
Doctests
Doctests are tests in a form of documentation of the function. Often, we provide them in stencil files. For example:
## 1: (Task 0.0.0) Absolute def my_abs(v): """ Input: a real number Output: the absolute value of the input >>> x = 7 >>> my_abs(x) 7 >>> my_abs(1 - x) + 2 8 """ pass
Doctests are great not only because they are tests that you can use, but also because you can run them via the module doctest. To invoke the module, type python3 -m doctest <a stencil file> in the REPL.
Now, suppose we replace pass with return v (which is wrong), we will get the following:$ python -m doctest mylab.py ********************************************************************** File "mylab.py", line 10, in mylab.my_abs Failed example: my_abs(1 - x) + 2 Expected: 8 Got: -4 ********************************************************************** 1 items had failures: 1 of 3 in mylab.my_abs ***Test Failed*** 1 failures.
Now, we change it to the right answer: return v if v >= 0 else -v. After running the doctest again, the output should be nothing since everything is correct.
The doctest module will run every doctests in a file. If you wish not to run them, you might consider commenting out functions that you do not want to test. Lastly, doctest will not work if you call print function in your file! One way to avoid the problem is to remove all print functions. The other way is to import sys at the top of the file, then change all print to print(..., file=sys.stderr) which will avoid the confict with doctest module.