Search code examples
pythonargparsepep8

PEP8 and initialization of object using long keyword arguments


It appears to me that there's no easy way to use the RawDescriptionHelpFormatter in the argparse module without either violating PEP8 or cluttering your namespace.

Here is the most obvious way to format it:

parser = argparse.ArgumentParser(prog='PROG',
                                 ....
                                 formatter_class=argparse.RawDescriptionHelpFormatter)

This violates the stipulation that lines should not exceed 80 characters

Here's how the example in the argparse documentation looks (spoiler: this is actually correct; see comments below):

parser = argparse.ArgumentParser(
    prog='PROG',
    formatter_class=argparse.RawDescriptionHelpFormatter,
    ....

This violates PEP8 E128 regarding the indentation of continuation lines.

Here'another possibility:

parser = argparse.ArgumentParser(
    prog='PROG',
    formatter_class=
    argparse.RawDescriptionHelpFormatter,
    ....

This violates PEP8 E251 regarding spaces around = for keyward arguments.

(Of course, this doesn't even address the fact that my character-count for the line assumes that the parser token starts on the first column, which is the best case scenario; what if we want to create a parser inside a class and/or a function?)

So the only remaining alternative, as far as I can tell, is to either clutter the namespace:

from argparse import RawDescriptionHelpFormatter, ArgumentParser

...or use a silly temporary variable (which also clutters the namespace):

rawformatter = argparse.RawDescriptionHelpFormatter
parser = argparse.ArgumentParser(prog='PROG',
                                 ....
                                 formatter_class=rawformatter)

Am I missing something? I guess having RawDescriptionHelpFormatter and ArgumentParser directly in the current namespace isn't a big deal, but this seems like an unnecessary frustration.


Solution

  • Your second example looks fine to me, and seems to match the "# Hanging indents should add a level." example here: http://legacy.python.org/dev/peps/pep-0008/#indentation

    Also seems to tally with this similar question/answer: What is PEP8's E128: continuation line under-indented for visual indent?