Search code examples
pythonpython-3.xcoding-stylepep8pep

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


I have a long code looks like this:

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

The 3rd line is too much long, and I am struggling where to make a break and start a new line that can make code more readable and clear.

I have tried this:

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

and

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

and

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

I prefer the first line breaking style. Which one do you prefer or do you have any other line breaking styles that looks clear and beautiful, please show me.


Solution

  • Since, the line get_encryption_phone_num(instance.receiver_phone_num) takes up a lot of space within the expression, it is better to assign its value to another variable and then use that variable instead within the expression just for the sake of readability.

    encryption_phone_num = get_encryption_phone_num(instance.receiver_phone_num)
    

    As far as indentation for your expression goes, you can go with any of the following:

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

    OR

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