Question

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.

Était-ce utile?

La solution

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

Autres conseils

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. ...

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top