Question

How can I automatically wrap long python strings so that they print correctly?

Specifically, I am trying to add help strings with optparse which I want to be able to modify easily.

I have found several methods of dealing with long strings, none of which allow me to refill after making changes using M-q in emacs or similar:

p.add_option('-a', help = "this is my\
                           long help text")

forces newlines in the result and doesn't allow refilling

p.add_option('-a', help = "this is my "
                          "long help text")

formats correctly but doesn't allow refilling

p.add_option('-a', help = '''
             this is my
             long help text
             ''')

formats incorrectly but does allow refilling

p.add_option('-a', help = dedent('''
             this is my
             long help text
             '''))

is the best option I've found, formats almost correctly and allows refilling but results in an additional space at the beginning of the string.

Was it helpful?

Solution 2

Use argparse instead of optparse, if you are using Python >= 2.7. It does dedent for you. You can just do:

parser.add_argument('--argument', '-a', help='''
    this is my
    long help text
    ''')

Even if you are using Python < 2.7, you can install argparse from pypi.

Note that there is a way to suppress this auto-dedent behavior. The link given by @msw is actually the section about it.

OTHER TIPS

The docs use dedent so it seems reasonable, especially if it works. If you want to drop the leading space you could:

help = dedent('''
             this is my
             long help text
             ''')[1:]

although

dedent(…).lstrip() 

might be more obvious.

I'm not 100% sure what refilling is, but here's what I typically use:

p.add_option('-a', help = ("this is my "
                           "long help text"))

(note the additional parenthesis). Emacs lines up the next line with the previous open parenthesis for me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top