DEV Community

Juha-Matti Santala
Juha-Matti Santala

Posted on

Is my code self-documenting?

So you know how some people say that "Good code documents itself"?

Is this what they meant?

def self_documenting_sum(a, b):
    with open(__file__, 'r') as source:
        data = source.read().split('\n')

    with open(__file__, 'w') as source:
        if not data[1].startswith('    "'):
            documentation = '    """Sums up two integers"""'
            new_source = data[:]
            new_source.insert(1, documentation)
            source.write('\n'.join(new_source))
        else:
            source.write('\n'.join(data))
    return a + b


print(self_documenting_sum(2,5))
Enter fullscreen mode Exit fullscreen mode

(It's a Python script that adds docstring to its only function on the first run.)

edit: I expanded on the idea a bit in hamatti/self-documenting-code

Top comments (0)