Python and PEP8 - Recommendations on breaking up long lines?
Steven D'Aprano
steve at pearwood.info
Wed Nov 27 22:57:03 EST 2013
On Wed, 27 Nov 2013 17:57:13 -0800, Victor Hooi wrote:
> Hi,
>
> I'm running pep8 across my code, and getting warnings about my long
> lines (> 80 characters).
>
> I'm wonder what's the recommended way to handle the below cases, and fit
> under 80 characters.
>
> First example - multiple context handlers:
>
> with open(self.full_path, 'r') as input,
> open(self.output_csv, 'ab') as output:
if True: # add indentation, just for the example's sake.
if True:
if True:
with (open(self.full_path, 'r') as input,
open(self.output_csv, 'ab') as output):
do_this()
do_that()
> Second example - long error messages:
>
> self.logger.error('Unable to open input or output file - %s.
> Please check you have sufficient permissions and the file
> and parent directory exist.' % e)
Long strings are always ugly :-(
But you can use implicit concatenation to make them a little less so.
if True: # add indentation, just for the example's sake.
if True:
if True:
self.logger.error(
'Unable to open input or output file - %s.'
' Please check you have sufficient permissions and
' the file and parent directory exist.'
% e)
Notice that my convention is to use a leading space in the strings when
doing implicit concatenation, if possible. E.g.:
("Hello"
" World!")
rather than:
("Hello "
"World!")
> Third example - long comments:
>
> """ NB - We can't use Psycopg2's parametised statements
> here, as that automatically wraps everything in single
> quotes. So s3://my_bucket/my_file.csv.gz would become
> s3://'my_bucket'/'my_file.csv.gz'. Hence, we use Python's
> normal string formating - this could potentially exposes us
> to SQL injection attacks via the config.yaml file.
> I'm not aware of any easy ways around this currently though
> - I'm open to suggestions though.
> See
> http://stackoverflow.com/questions/9354392/psycopg2-cursor-
execute-with-sql-query-parameter-causes-syntax-error
> for further information. """
>
> In this case, I'm guessing a using triple quotes (""") is a better idea
> with multi-line comments, right?
*shrug* That's a matter of personal preference.
> However, I've noticed that I can't seem to put in line-breaks inside the
> comment without triggering a warning. For example, trying to put in
> another empty line in between lines 6 and 7 above causes a warning.
>
> Also, how would I split up the long URLs? Breaking it up makes it
> annoying to use the URL. Thoughts?
I hate long URLs.
There's no good solution to long URLs. Just leave them as they come, and
if your style checker allows you to flag an exception to the long-line
rules, use it.
--
Steven
More information about the Python-list
mailing list