WilliamKF
WilliamKF

Reputation: 43149

Avoiding long lines of code in Python

I try and keep my code within 80 characters wide so it is easy to see side by side in a standard window I set up. In doing this, I have a Python v2.7 construct like this:

subseq_id_to_intervals_dict, subseq_id_to_ccid_formats_dict, subseq_id_to_min_max_count_dict = map_cases(opts,
                                            format_to_ccid_funcs,
                                            sys.stdin)

So I broke it up like this:

subseq_id_to_intervals_dict,
subseq_id_to_ccid_formats_dict,
subseq_id_to_min_max_count_dict = map_cases(opts,
                                            format_to_ccid_funcs,
                                            sys.stdin)

But that caused errors

NameError: name 'subseq_id_to_intervals_dict' is not defined

Until I added backslashes:

subseq_id_to_intervals_dict,        \
subseq_id_to_ccid_formats_dict,     \
subseq_id_to_min_max_count_dict = map_cases(opts,
                                            format_to_ccid_funcs,
                                            sys.stdin)

Why is it that the comma at the end of the line does not inform Python sufficiently to understand the syntax and not get an error? Is there a cleaner way to do this without backslashes?

Upvotes: 6

Views: 653

Answers (1)

David Robinson
David Robinson

Reputation: 78610

You could put the left side of the assignment into parentheses:

(subseq_id_to_intervals_dict,
 subseq_id_to_ccid_formats_dict,
 subseq_id_to_min_max_count_dict) = map_cases(opts,
                                            format_to_ccid_funcs,
                                            sys.stdin)

The left side is already a tuple- the parentheses just imply the line continuation. The line

subseq_id_to_intervals_dict,

doesn't imply a line continuation because it is a complete statement- it's a tuple with a single element.

Upvotes: 12

Related Questions