whan whan - 2 months ago 8x
Python Question

Is it a good practice to parse doc string?

I have some python methods with instructions. For example, parameter combinations to be tested. In a count-part of my code, I use a parser for the doc-string of the function that I use so that a configuration file is no longer needed. The information I need are solely contained in the functions doc string. I wonder if this is a good and common practice in industry?

update: I have a long list of experiments to do, represented by functions. For each function, I have some test cases (different for different functions). When I create the function, the test cases are defined. I put them in the doc string and parse them when I do the test.

def my_function1(param1,param2)
'''param1: 10, 20, 40, 60; param2: 5, 10, 20, 40;'''

return something

def my_function2(param1,param2,param3)
'''param1: 10, 20, 40, 60; param2: 5, 10, 20, 40; param3: 100, 200'''
return something


It is convenient to me in this case to save the test cases into doc string not separately. But I am not sure parsing a doc string is a safe practice.


Edit: Here are the PEP suggestions: https://www.python.org/dev/peps/pep-0257/#specification

I am fairly confident that this is not common practice, and my instinct is that it is not good practice either.

First, some example Docstrings from Python standard library modules.

When I type help for combinations:

combinations(iterable, r) --> combinations object

Return successive r-length combinations of elements in the iterable.

combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)

This is the help for sum:

sum(sequence[, start]) -> value

Return the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0).  When the sequence is
empty, return start.

These docstrings elaborate in English.

The goal of a docstring according to Python core developers seems to be to explicitly show how to use the methods, and to clear up any doubt. I would suggest that your practice is wrong because you are mixing in different goals, different kinds of logic into your docstrings.

If I were you, I would isolate and separate your goals instead of combining everything into your docstrings. I would keep the logic of your test cases, and of your configuration in separate places designated for that logic.

In general in programming, I believe keeping your different goals isolated is part of what "best practices" encapsulates.

I should admit, though, that from reading your question I'm not confident that I completely understand what you're asking, or what you're doing with your testing and configuration.