I’ve written a Python API that is “chain based” (similar to jQuery). So I can write:
myObject.doStuff().doMoreStuf().goRed().goBlue().die()
The problem is that I haven’t found a way to keep the syntax clean with long chains. In JavaScript I could simply do
myOjbect
.doStuf()
.doMoreStuf()
.goRed()
.goBlue()
.die()
but Python has indentation restrictions…
PEP8-compliant solution: formatting the line
Actually PEP8 says:
So I suppose your code should look like this:
Alternative solutions: splitting into separate statements
Judging from the syntax, there are two options possible regarding the values returned by each method call:
die(), which is not required, as its result is not being used) returns modified instance (the same instance, on which it was called).die()is not required to do that) returns copy of the instance on which it was called.Solution for mutable objects (methods return original instance)
In first case (when returning same instance), the solution to split longer lines into several statements is:
Real world example involves mutable objects:
(although
list.append()does not return anything, just for consistency and for stating explicitly that it is mutable)Solution for immutable objects (methods return modified copy)
In the second case (when returning copy), the solution to do similar thing is:
Real world example involves immutable objects: