-3

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.

Melvin Abraham
  • 2,870
  • 5
  • 19
  • 33
Gorgine
  • 310
  • 2
  • 11
  • It really comes down to personal preference only, just make sure that the formatting is consistent in all your scripts, or among all your teammates if you're working as a team. – kennysliding Nov 18 '20 at 04:22

1 Answers1

1

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
)
Melvin Abraham
  • 2,870
  • 5
  • 19
  • 33