2

In Python3.2 I can do this:

foo = Bar()
foo.setSomething(something1).setStatus('horizontal').setAttributes(attributes)

Eventually the chain becomes pretty long. I have an itch for a vertical chaining.

foo = Bar()
foo.setSomething(something1)
   .setStatus('vertical')
   .setAttributes(attributes)

Is there any way to do that?

nkamm
  • 627
  • 5
  • 14
  • http://stackoverflow.com/questions/2550439/correct-way-to-put-long-function-calls-on-multiple-lines – sean Dec 03 '12 at 14:52
  • http://stackoverflow.com/questions/53162/how-can-i-do-a-line-break-line-continuation-in-python – asheeshr Dec 03 '12 at 15:03
  • Thank you guys for links. Could not find any of these questions since I was looking by keyword "chaining" :) – nkamm Dec 03 '12 at 15:08

2 Answers2

2

Just enclose your expression in parenthesis:

foo = Bar()
(foo.setSomething(something1)
     .setStatus('vertical')
     .setAttributes(attributes))
Krotton
  • 9,561
  • 3
  • 15
  • 12
2

Thank you @Krotton for the answer it works indeed. Also thanks to @sean for the link. So, the correct way to use vertical chaining is:

foo = Bar()
(foo.setSomething(something1)
     .setStatus('vertical')
     .setAttributes(attributes))

You also may use the syntax, like with multi-line strings, to allow vertical chaining:

foo = Bar()
foo.setSomething(something1)\
   .setStatus('vertical')\
   .setAttributes(attributes)
Community
  • 1
  • 1
nkamm
  • 627
  • 5
  • 14