python-deployer icon indicating copy to clipboard operation
python-deployer copied to clipboard

Don't add extra newline after indented block

Open janfabry opened this issue 12 years ago • 3 comments

Only replace the newlines that were initially there.

janfabry avatar May 23 '13 09:05 janfabry

I think this could be okay, but why exactly deed you need it? Normally, there's a reason why for instance a print statement appends \n to every line.

jonathanslenders avatar May 23 '13 18:05 jonathanslenders

I used it in the following situation:

"""
MY_CONFIG = (
    'A',
    'B',
    %(extra_config)s,
    'C',
)
""" % {'extra_config': indent(extra_config_var)}

There, the extra newline gives a syntax error.

janfabry avatar May 24 '13 11:05 janfabry

Jan, can you update this patch again that we can merge it? Python 3.3 has a textwrap.indent function. I'd like to have this behaviour identical, if possible. (Not sure if it's the same as your patch.)

See this thread: http://bugs.python.org/issue13857

And this patch: http://hg.python.org/cpython/rev/6f7afe25d681 {{{

4.17 +def indent(text, prefix, predicate=None):
4.18 +    """Adds 'prefix' to the beginning of selected lines in 'text'.
4.19 +
4.20 +    If 'predicate' is provided, 'prefix' will only be added to the lines
4.21 +    where 'predicate(line)' is True. If 'predicate' is not provided,
4.22 +    it will default to adding 'prefix' to all non-empty lines that do not
4.23 +    consist solely of whitespace characters.
4.24 +    """
4.25 +    if predicate is None:
4.26 +        def predicate(line):
4.27 +            return line.strip()
4.28 +
4.29 +    def prefixed_lines():
4.30 +        for line in text.splitlines(True):
4.31 +            yield (prefix + line if predicate(line) else line)
4.32 +    return ''.join(prefixed_lines())

}}}

jonathanslenders avatar Jul 31 '13 08:07 jonathanslenders