Reputation: 377
I have a function call in python 2.7:
execute_cmd('/sbin/ip addr flush dev '
+ args.interface
+ ' && '
+ '/sbin/ifdown '
+ args.interface
+ ' ; '
+ '/sbin/ifup '
+ args.interface
+ ' && '
+ '/sbin/ifconfig | grep '
+ args.interface)
This is running fine, but pylint
is complaining with the following warning messages:
C:220, 0: Wrong continued indentation (remove 1 space).
+ args.interface
|^ (bad-continuation)
C:221, 0: Wrong continued indentation (remove 1 space).
+ ' && '
|^ (bad-continuation)
C:222, 0: Wrong continued indentation (remove 1 space).
+ '/sbin/ifconfig | grep '
|^ (bad-continuation)
.
.
.
What is the correct way to call a function in python with string argument(s) which spans across multiple lines?.
Upvotes: 0
Views: 2499
Reputation: 41
I'd like to highlight the position of +
, as pointed out in this post
Best practice:
income = (gross_wages
+ taxable_interest)
Anti-pattern: (In PEP8, this is W504 line break after binary operator)
income = (gross_wages +
taxable_interest)
Upvotes: 0
Reputation: 20237
PEP 8 states that you can also start a long argument list (or anything within brackets, really) at the next line with one extra indentation level:
execute_cmd(
'/sbin/ip addr flush dev ' +
args.interface +
' && ' +
'/sbin/ifdown ' +
args.interface +
' ; ' +
'/sbin/ifup ' +
args.interface +
' && ' +
'/sbin/ifconfig | grep ' +
args.interface
)
As I said in my comment, binary operators should be put at the end of a line break, not at the start of a new one.
What you can also do is use an fstring
(python >3.6) and just drop the +
s:
execute_cmd(
f'/sbin/ip addr flush dev {args.interface} && /sbin/ifdown'
f' {args.interface} ; /sbin/ifup {args.interface} && '
f'/sbin/ifconfig | grep {args.interface}'
)
The same with the .format
function (from python .. 2.6 onwards I think?):
execute_cmd(
'/sbin/ip addr flush dev {0} && /sbin/ifdown' +
' {0} ; /sbin/ifup {0} && ' +
'/sbin/ifconfig | grep {0}'.format(args.interface)
)
Upvotes: 0
Reputation: 6075
Pylint tells you exactly what to do, remove one space:
execute_cmd('/sbin/ip addr flush dev '
+ args.interface
+ ' && '
+ '/sbin/ifdown '
+ args.interface
+ ' ; '
+ '/sbin/ifup '
+ args.interface
+ ' && '
+ '/sbin/ifconfig | grep '
+ args.interface)
Also, you could use string formatting, for example:
command_line = '/sbin/ip addr flush dev {0} && /sbin/ifdown {0} ; /sbin/ifup {0} && {0} /sbin/ifconfig | grep {0}'\
.format(args.interface)
Upvotes: 1