You can use Python ๐ docstrings to provide usage examples of your functions!
That's useful to your users!
And did you know that you can use those examples to do small automatic tests on your functions? ๐ฑ
Let me break down how in a mini thread ๐๐งต
First off, we define a simple function.
In this case, we just define a function to return the successor of an integer:
Then, we define a basic docstring for the function, in a single line.
However, we also add an example showing how using the function looks like.
Notice that the example looks like the REPL:
Now, we can turn that example into a small test as well!
We just need to import `doctest`, which is in the standard library.
We import it, and run `testmod`, to test the current "module":
If your code agrees with the examples you gave, no output is shown.
So, for the sake of demonstration, let's introduce a small bug in the code, with the wrong return value:
Now that there is a bug, the code no longer agrees with the example in the docstring!
When that is the case, we get some output saying something is wrong:
Pretty cool, right?!
This can be useful if you use it sparingly, with a couple of basic usage examples/small tests in your functions' docstrings.
For extensive testing of your code, I recommend using a testing framework!
By the way, which one do you use?
Was this thread useful? I hope so!
If you want to have some high-quality Python ๐ content in your timeline, make sure to follow me @mathsppblog ๐
Also, feel free to retweet the beginning of this thread to help your friends improve their Python ๐ช
I'm sorry, everyone.
A formatting issue kind of ruined the code. This is what I wanted to share:
Notice the REPL-like input with >>> and the (correct/expected) result in the next line.
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.