Reputation: 14674
I generally wrap long lines using parenthesis as suggested in PEP8:
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.
But in the case of a long line like this one, I'm not sure what the recommended way would be:
my_object = my_toolbox_with_a_pretty_long_name.some_subset_with_a_pretty_long_name_too.here_is_what_i_was_looking_for
The point is that even the part after the =
sign is still too long and I don't know where/how to cut.
I often do
toolbox = my_toolbox_with_a_pretty_long_name
subset = toolbox.some_subset_with_a_pretty_long_name_too
my_object = subset.here_is_what_i_was_looking_for
but it is a bit different as it creates intermediate variables, although functionally it is equivalent. Also, I can't really do that if the line is in a multiple condition, like if a is not None and len(my_toolbox_..._for) == 42
.
This also works:
my_object = (
my_toolbox_with_a_pretty_long_name
).some_subset_with_a_pretty_long_name_too.here_is_what_i_was_looking_for
my_object = ((my_toolbox_with_a_pretty_long_name
).some_subset_with_a_pretty_long_name_too
).here_is_what_i_was_looking_for
but it's pretty bad in terms of readability and suggesting this to avoid a 85-ish character line makes me look like a PEP8 nazi. And I can't even get the latter to please both pylint and flake8.
Upvotes: 2
Views: 70
Reputation: 74655
You only need one pair of parentheses:
my_object = (my_toolbox_with_a_pretty_long_name
.some_subset_with_a_pretty_long_name_too
.here_is_what_i_was_looking_for)
Line breaks are not significant in parenthesized expressions, they can occur anywhere white-space is permitted.
For your other example:
if (a is not None
and len(my_toolbox_with_a_pretty_long_name
.some_subset_with_a_pretty_long_name_too
.here_is_what_i_was_looking_for) == 42):
Upvotes: 4