python2.7换行符,Python的换行符换行符

I have some code like this. Should the break occur before the periods or after?

# before

my_var = somethinglikethis.where(we=do_things).where(we=domore).where(we=everdomore)

# this way

my_var = somethinglikethis.where(we=do_things) \

.where(we=domore) \

.where(we=everdomore)

# or this way

my_var = somethinglikethis.where(we=do_things). \

where(we=domore). \

where(we=everdomore)

解决方案

Personally, I prefer using parenthesis so that you don't need \:

my_var = (somethinglikethis

.where(we=do_things)

.where(we=domore)

.where(we=everdomore))

(I changed the indentation because that's how my editor indents it automatically.)

I just looked through PEP 8, and it looks like there's no mention of line breaks.

But parenthesis (or other characters such as [] or {}) should help your editor indent the code automatically, and they only require you to modify the beginning and the end of the expression.

[Edit]

Here is what the style guide says about it, thanks to delnan:

The preferred way of wrapping long lines is by using Python's implied line

continuation inside parentheses, brackets and braces. Long lines can be

broken over multiple lines by wrapping expressions in parentheses. These

should be used in preference to using a backslash for line continuation.

Make sure to indent the continued line appropriately. The preferred place

to break around a binary operator is after the operator, not before it.

Some examples:

class Rectangle(Blob):

def __init__(self, width, height,

color='black', emphasis=None, highlight=0):

if (width == 0 and height == 0 and

color == 'red' and emphasis == 'strong' or

highlight > 100):

raise ValueError("sorry, you lose")

if width == 0 and height == 0 and (color == 'red' or

emphasis is None):

raise ValueError("I don't think so -- values are %s, %s" %

(width, height))

Blob.__init__(self, width, height,

color, emphasis, highlight)

[Edit]

The style guide now recommends breaking before a binary operator (thanks @Neapolitan):

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值