Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: split method call into multiple lines

Tags:

python

In JavaScript I can do something like:

var template = "{a}{b}-{c}{d}";
var myStuff = template
                .replace("{a}", a)
                .replace("{b}", b)
                .replace("{c}", c)
                .replace("{d}", d);

I would like to do something similar in python, but due to the fact that python uses indentation for blocks of code, I can't simply write:

myStuff = template
                .replace("{a}", a)
                .replace("{b}", b)
                .replace("{c}", c)
                .replace("{d}", d)

I don't want to have to write this:

myStuff = template.replace("{a}", a).replace("{b}", b).replace("{c}", c).replace("{d}", d)

Or this:

myStuff = template
myStuff = myStuff.replace("{a}", a)
myStuff = myStuff.replace("{b}", b)
myStuff = myStuff.replace("{c}", c)
myStuff = myStuff.replace("{d}", d)

They both look ugly (and I don't like my code ugly!).
Is there a way to break a method call chain into new lines in python, just like I did in JavaScript?

like image 415
Daniel Gruszczyk Avatar asked Aug 07 '15 09:08

Daniel Gruszczyk


2 Answers

In general your only hope is to use line joining. You can always use explicit line joining

myStuff = template \
            .replace("{a}", a) \
            .replace("{b}", b) \
            .replace("{c}", c) \
            .replace("{d}", d)

To use implicit line joining you have to come up with somewhere to put parenthesis (implicit line joining is when you have something within paretheses, brackets or braces - if split over several lines the identation does not take effect). For example

 myStuff = (template.replace("{a}", a)
            .replace("{b}", b)
            .replace("{c}", c)
            .replace("{d}", d))

Then of course you can probably find special solutions for specific situations, like using string formatting in your example:

 myStuff = template.format(a=a, b=b, c=c, d=d)

but that will not work if you're trying to replace something entirely else (it also doesn't fail if a, b, c or d happens to be something else than a string).

like image 167
skyking Avatar answered Oct 05 '22 23:10

skyking


Other answers would get you how to split a statement into multiple lines, But an easier way to achieve what you are doing would be to use str.format() -

>>> template = "{a}{b}-{c}{d}"
>>> a = 1
>>> b = 2
>>> c = 3
>>> d = 4
>>> template.format(**{'a':a,'b':b,'c':c,'d':d})
'12-34'
>>> template.format(a=a,b=b,c=c,d=d)
'12-34'

The first str.format() unpacks a dictionary into keyword arguments for the function format() (similar to what the second one does directly) .


Also, you can split the arguments to a function call in multiple lines without having to use \ , Example -

>>> template.format(a=a,
...                 b=b,
...                 c=c,
...                 d=d)
'12-34'
like image 38
Anand S Kumar Avatar answered Oct 06 '22 00:10

Anand S Kumar