Search code examples
pythonpython-2.7argparsepylintdocstring

Cannot access __doc__ from argparse without redefining it


I have a module in which a define a module __doc__ string (multiline) which I also want to use in my argparse usage.

So at first I defined it as

'''My
multiline
module
doc-string
'''

and used it in the following way

parser = argparse.ArgumentParser(description=str(__doc__),
                                formatter_class=SmartFormatter)

(Note: left out the SmartFormatter class since it is not part of the problem).

When I now give the -h option it prints None where the doc-string should be.

I can solve it easily by defining the doc-string as follows:

__doc__ = '''My
multiline
module
doc-string
'''

But then pylint starts complaining:

<file.py>:<line>: [W0622(redefined-builtin), ] Redefining built-in '__doc__'

So now is my question how I can access the module doc-string without redefining __doc__, preferably I don't want to ignore the W0622 warning.


Solution

  • The value for __doc__ is None only if you didn't put that multi-line string as the first statement of the file (only comments can precede it).

    Once you have the string object appear in the right location, __doc__ will no longer be set to None, passing it to argparse will work and doesn't need to be re-defined.

    Note that if you run your code with the -OO command-line switch, docstrings are dropped entirely.

    As for disabling pylint warnings connected to a multi-line string, you can use a pair of comments to disable specific warnings for a few lines, then re-enabling them afterwards:

    # pylint: disable=W0622
    __doc__ = """\
    # ...
    """
    # pylint: enable=W0622