2

Possible Duplicate:
How to break a line of chained methods in Python?

Following question is about python codestyle and may be design of reusable lib. So I have builder that chains graph creation into single big line as follow:

graph.builder() \
        .push(root) \
        .push(n1) \
        .arc(arcType) \ #root-arc-n1 error is there
        .push(n2) \
...

At line #4 I get the error about wrong symbol (#). So general question how to produce well commented code against long builder path. Also as a good answer I'll appreciate suggestion on changes in builder to allow comments for clarifying code.

Community
  • 1
  • 1
Dewfy
  • 23,277
  • 13
  • 73
  • 121

3 Answers3

1

You can best do that by using intermediate variables:

builder = graph.builder()
builder = builder.push(root).push(n1)
builder = builder.arc(arcType)  #root-arc-n1 error is there
builder = builder.push(n2). # ... etc. ...
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Wrapping the entire thing in parentheses forces python to treat it as a single expression:

(graph.builder()
    .push(root)
    .push(n1)
    .arc(arcType) #root-arc-n1 error is there
    .push(n2)
)

I might be tempted to rework your builder method to allow:

graph.builder(lambda g: g
    .push(root)
    .push(n1)
    .arc(arcType) #root-arc-n1 error is there
    .push(n2)
)

Just to make the location of parentheses more sensible

Eric
  • 95,302
  • 53
  • 242
  • 374
0

It doesn't look too good but this allows you to use inline comments:

graph.builder(
    ).push(root
    ).push(n1
    ).arc(arcType #root-arc-n1 error is there
    ).push(n2)

http://www.python.org/dev/peps/pep-0008/#maximum-line-length

mpaolini
  • 1,334
  • 10
  • 7