如何打破 Python 中的一系列链式方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4768941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:26:16  来源:igfitidea点击:

How to break a line of chained methods in Python?

pythoncoding-stylepep8

提问by Juliusz Gonera

I have a line of the following code (don't blame for naming conventions, they are not mine):

我有以下一行代码(不要怪命名约定,它们不是我的):

subkeyword = Session.query(
    Subkeyword.subkeyword_id, Subkeyword.subkeyword_word
).filter_by(
    subkeyword_company_id=self.e_company_id
).filter_by(
    subkeyword_word=subkeyword_word
).filter_by(
    subkeyword_active=True
).one()

I don't like how it looks like (not too readable) but I don't have any better idea to limit lines to 79 characters in this situation. Is there a better way of breaking it (preferably without backslashes)?

我不喜欢它的样子(不太可读),但在这种情况下,我没有更好的主意将行数限制为 79 个字符。有没有更好的方法来打破它(最好没有反斜杠)?

采纳答案by sth

You could use additional parenthesis:

您可以使用额外的括号:

subkeyword = (
        Session.query(Subkeyword.subkeyword_id, Subkeyword.subkeyword_word)
        .filter_by(subkeyword_company_id=self.e_company_id)
        .filter_by(subkeyword_word=subkeyword_word)
        .filter_by(subkeyword_active=True)
        .one()
    )

回答by Ivo van der Wijk

Just store the intermediate result/object and invoke the next method on it, e.g.

只需存储中间结果/对象并在其上调用下一个方法,例如

q = Session.query(Subkeyword.subkeyword_id, Subkeyword.subkeyword_word)
q = q.filter_by(subkeyword_company_id=self.e_company_id)
q = q.filter_by(subkeyword_word=subkeyword_word)
q = q.filter_by(subkeyword_active=True)
subkeyword = q.one()

回答by Haozhun

According to Python Language Reference
You can use a backslash.
Or simply break it. If a bracket is not paired, python will not treat that as a line. And under such circumstance, the indentation of following lines doesn't matter.

根据Python Language Reference
您可以使用反斜杠。
或者干脆打破它。如果括号未配对,python 不会将其视为一行。在这种情况下,以下行的缩进无关紧要。

回答by minhee

You seems using SQLAlchemy, if it is true, sqlalchemy.orm.query.Query.filter_by()method takes multiple keyword arguments, so you could write like:

你似乎在使用 SQLAlchemy,如果是真的,sqlalchemy.orm.query.Query.filter_by()方法需要多个关键字参数,所以你可以这样写:

subkeyword = Session.query(Subkeyword.subkeyword_id,
                           Subkeyword.subkeyword_word) \
                    .filter_by(subkeyword_company_id=self.e_company_id,
                               subkeyword_word=subkeyword_word,
                               subkeyword_active=True) \
                    .one()

But it would be better:

但它会更好:

subkeyword = Session.query(Subkeyword.subkeyword_id,
                           Subkeyword.subkeyword_word)
subkeyword = subkeyword.filter_by(subkeyword_company_id=self.e_company_id,
                                  subkeyword_word=subkeyword_word,
                                  subkeyword_active=True)
subkeuword = subkeyword.one()

回答by pkoch

My personal choice would be:

我个人的选择是:

subkeyword = Session.query(
    Subkeyword.subkeyword_id,
    Subkeyword.subkeyword_word,
).filter_by(
    subkeyword_company_id=self.e_company_id,
    subkeyword_word=subkeyword_word,
    subkeyword_active=True,
).one()

回答by Raymond Hettinger

This is a case where a line continuation character is preferred to open parentheses. The need for this style becomes more obvious as method names get longer and as methods start taking arguments:

在这种情况下,换行符优先于开括号。随着方法名称变得更长并且方法开始接受参数,对这种风格的需求变得更加明显:

subkeyword = Session.query(Subkeyword.subkeyword_id, Subkeyword.subkeyword_word) \
                    .filter_by(subkeyword_company_id=self.e_company_id)          \
                    .filter_by(subkeyword_word=subkeyword_word)                  \
                    .filter_by(subkeyword_active=True)                           \
                    .one()

PEP 8 is intend to be interpreted with a measure of common-sense and an eye for both the practical and the beautiful. Happily violate any PEP 8 guideline that results in ugly or hard to read code.

PEP 8 旨在以常识和实用和美观的眼光来解释。高兴地违反任何导致难看或难以阅读的代码的 PEP 8 准则。

That being said, if you frequently find yourself at odds with PEP 8, it may be a sign that there are readability issues that transcend your choice of whitespace :-)

话虽如此,如果您经常发现自己与 PEP 8 不一致,这可能表明存在超出您选择的空白的可读性问题:-)

回答by árni St. Siguresson

It's a bit of a different solution than provided by others but a favorite of mine since it leads to nifty metaprogramming sometimes.

它与其他人提供的解决方案略有不同,但却是我的最爱,因为它有时会导致漂亮的元编程。

base = [Subkeyword.subkeyword_id, Subkeyword_word]
search = {
    'subkeyword_company_id':self.e_company_id,
    'subkeyword_word':subkeyword_word,
    'subkeyword_active':True,
    }
subkeyword = Session.query(*base).filter_by(**search).one()

This is a nice technique for building searches. Go through a list of conditionals to mine from your complex query form (or string-based deductions about what the user is looking for), then just explode the dictionary into the filter.

这是构建搜索的好方法。浏览一个条件列表,从您的复杂查询表单中挖掘(或基于字符串的关于用户正在查找的内容的推断),然后将字典分解到过滤器中。

回答by acgtyrant

I like to indent the arguments by two blocks, and the statement by one block, like these:

我喜欢将参数缩进两个块,将语句缩进一个块,如下所示:

for image_pathname in image_directory.iterdir():
    image = cv2.imread(str(image_pathname))
    input_image = np.resize(
            image, (height, width, 3)
        ).transpose((2,0,1)).reshape(1, 3, height, width)
    net.forward_all(data=input_image)
    segmentation_index = net.blobs[
            'argmax'
        ].data.squeeze().transpose(1,2,0).astype(np.uint8)
    segmentation = np.empty(segmentation_index.shape, dtype=np.uint8)
    cv2.LUT(segmentation_index, label_colours, segmentation)
    prediction_pathname = prediction_directory / image_pathname.name
    cv2.imwrite(str(prediction_pathname), segmentation)