[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Spread a statement over various lines

On 17.09.19 20:59, Manfred Lotz wrote:
> I have a function like follows
> def regex_from_filepat(fpat):
>     rfpat = fpat.replace('.', '\\.') \
>                       .replace('%', '.')  \
>                       .replace('*', '.*')
>     return '^' + rfpat + '$'
> As I don't want to have the replace() functions in one line my
> question is if it is ok to spread the statement over various lines as
> shown above, or if there is a better way?

One problem with explicit line continuation using \ is that it is
dependent on the backslash being the last character on the line, i.e.
a single space at the end of the line will result in a SyntaxError.
This is why implicit line continuation relying on opened parentheses,
brackets or curly braces is often preferred, and recommended over
backslash continuation in PEP8
To use implicit line continuation you could either introduce extra
surrounding parentheses as suggested by others, or you may make use
of the parentheses you have already, like so:

def regex_from_filepat(fpat):
    rfpat = fpat.replace(
        '.', '\\.'
        '%', '.'
        '*', '.*'

    return '^' + rfpat + '$'