4

According to PEP 8:

When using a hanging indent the following considerations should be applied; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line.

Suppose I have something like:

my_object = VeryLongClassName(long_function_name(arg1, arg2), arg3)

which goes over 79 characters. Should I break like this:

my_object = VeryLongClassName(
        long_function_name(arg1, arg2), arg3)

or this?

my_object = VeryLongClassName(long_function_name(
        arg1, arg2), arg3)
EMBLEM
  • 2,207
  • 4
  • 24
  • 32

1 Answers1

2

I use the following approach, which scales nicely across a wide variety of situations and tends to keeps lines short -- and thus makes the code easier to scan visually.

my_object = VeryLongClassName(
    long_function_name(arg1, arg2),
    arg3,
)

There are a few added benefit of that approach:

  • It is widely used when defining large data structures (lists, dicts, and even JSON). It's handy to use a coding style that mimics your data layout style. Code is just another form of data, right?

  • It works great with most text editors, which approach the world from a line-oriented perspective. If each argument to a function or constructor is on a separate line, code refactoring is easy.

  • Its application is rule-based and purely mechanical. I never have to puzzle over how to indent the code.

  • As a result, it looks tidy and the governing principles are immediately clear. As a point of contrast, the indenting examples seen in PEP 8 look like a hodgepodge to my eye and thus don't provide very clear guidance.

Another strategy is to use local convenience variables, especially in situations where you need to use long names several times within a method. Although creating short mnemonics runs a risk of making code more obscure, it often helps with readability, provided that your code is already organized in fairly small functions or methods -- again because it tends to enhance the ease of visually scanning of the code.

vlcn = VeryLongClassName
lfn = long_function_name
x = vlcn(lfn(arg1, arg2), arg3)
y = vlcn(lfn(arg4, arg5), arg6)
Community
  • 1
  • 1
FMc
  • 41,963
  • 13
  • 79
  • 132