Skip to content
This repository has been archived by the owner on Dec 21, 2022. It is now read-only.

Don't add extra newline after indented block #15

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

janfabry
Copy link
Contributor

Only replace the newlines that were initially there.

Only replace the newlines that were initially there.
@jonathanslenders
Copy link
Owner

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.

@janfabry
Copy link
Contributor Author

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.

@jonathanslenders
Copy link
Owner

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 jonathanslenders force-pushed the master branch 2 times, most recently from cf54f50 to 32c1030 Compare October 21, 2014 08:59
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants