你通常如何处理 Python 中的长行代码换行符?

How do you usually handle long-line code newline breaking in Python?

我有一个长代码如下所示:

def to_representation(self, instance):
    res = super().to_representation(instance)
    res['receiver_phone_num'] = get_encryption_phone_num(instance.receiver_phone_num) if instance.receiver_phone_num else None
    return res

第 3 行太长,我正在纠结在哪里休息并开始新的一行,这样可以使代码更易读和清晰。

我试过这个:

res['receiver_phone_num'] = get_encryption_phone_num(
    instance.receiver_phone_num
) if instance.receiver_phone_num else None

res['receiver_phone_num'] = get_encryption_phone_num(instance.receiver_phone_num)\
    if instance.receiver_phone_num else None

res['receiver_phone_num'] = get_encryption_phone_num(
    instance.receiver_phone_num) if instance.receiver_phone_num else None

我更喜欢第一行断行样式。你更喜欢哪一种,或者你有没有其他看起来清晰漂亮的断线样式,请告诉我。

因为行 get_encryption_phone_num(instance.receiver_phone_num) 在表达式中占据了很多 space ,所以最好将其值赋给另一个变量,然后在表达式中使用该变量来代替为了可读性。

encryption_phone_num = get_encryption_phone_num(instance.receiver_phone_num)

就表达式的缩进而言,您可以使用以下任何一种:

res['receiver_phone_num'] = (encryption_phone_num
                            if instance.receiver_phone_num
                            else None)

res['receiver_phone_num'] = (
    encryption_phone_num
    if instance.receiver_phone_num
    else None
)