1

I need to modify docstrings in a bunch of files, to add the default values of input parameters to them, if present in the class constructor or the function signature.

So let say, I have the following given:

# a bunch of code

class A:
    """A good class.

    Parameters
    ----------
    p : int
        A powerful parameter.

    q : float, optional
        An even more powerful parameter.
    """
    def __init__(self, p=3, q=.3):
        self.p = p
        self.q = q

# a bunch of more code

I need to go through the whole file, find all such instances, and change them to:

# a bunch of code

class A:
    """A good class.

    Parameters
    ----------
    p : int, optional (default=3)
        A powerful parameter.

    q : float, optional (default=.3)
        An even more powerful parameter.
    """
    def __init__(self, p=3, q=.3):
        self.p = p
        self.q = q

# a bunch of more code

And then save it back to the same or a different file.

I'm trying to make sure the default values are mentioned in docstrings, which is pretty easy for a human to do, but I'm hoping I don't have to go through the whole package manually.

adrin
  • 4,511
  • 3
  • 34
  • 50
  • 1
    I believe this plus a parser should be enough https://stackoverflow.com/questions/713138/getting-the-docstring-from-a-function (basically change the docstring to whatever, the work is in the parser you'll have to write) – E.Serra Sep 18 '18 at 08:23

1 Answers1

0

This is exactly what you want to do:

1- Access the docstring of every method and modify it to include the default values

this requires: 1.1- Listing the attributes 1.2- Doing something on each attribute

modify = [a for a in dir(A) if not (a.startswith('__') and a.endswith('__'))]

(Surely there is a way of checking if an attribute is private, this is just a quick way)

Then for your list of attributes to modify you want the default values, use inspect:

import inspect

inspect.getfullargspec(<YOURATTRIBUTE HERE>)

FullArgSpec(args=['self', 'p', 'q'], varargs=None, varkw=None, defaults=(3, .3), kwonlyargs=[], kwonlydefaults=None, annotations={})

All you need to do now is use that information to modify the docstring

E.Serra
  • 1,495
  • 11
  • 14
  • Yes, this is the part I knew. 1. you're assuming I'm given an opject, or a class name, but I'm given a file, and I need to preserve everything else I don't touch in the file, like comments at the beginning, etc. 2. I know it's not too hard, but I'm hoping I don't have to parse the docstrings myself. I've seen CI pipelines (I guess circle-ci, or travis-ci) checking the docstrings as well. So I'm hoping to use whatever they use for the matter. – adrin Sep 18 '18 at 08:40