When programming in a scripting language (Python, Perl, Ruby or R), I try to write functions and keep them in separate files to keep my code modular.
For debugging, I often put the arguments of the function inside the function body and un-comment them as soon as I'm done.
Moreover, I often place a call to the function right after its definition, which I also uncomment when I'm done testing.
So in the end, my file looks like this
def add(a, b):
# a = 1
# b = 2
c = a + b
return c
# add(1, 2)
Is there a more elegant way to achieve this?
Moreover, I think common practice would be to remove these comments when shipping the code to others. Is there a way to achieve this in a JavaDoc like manner, while keeping "real" comments (i.e. not uncommented code)?
I should mention, that I often write wrapper functions around calls to plot functions in Matplotlib or R (ggplot, etc) and since in these cases the output is a graph, it doesn't fit so well into test-driven development frameworks.
答案 0 :(得分:0)
The proper way would be to write some unit tests.
If you want to have your tests very close to a source code, you should check out doctest module, it allows you to run tests placed directly in doc comments.
Neat thingy.
Edit:
In yours example it would look like this:
def add(a, b):
""" Returns sum of a and b
>>> add(1, 2)
3
"""
c = a + b
return c
And run the tests like this:
python -m doctest -v yourFile.py