【问题标题】:How can I better structure this code?我怎样才能更好地构造这段代码?
【发布时间】:2010-10-21 12:04:41
【问题描述】:

我有一个从 RESTful Web 服务获得的 lxml.objectify 数据结构。如果存在,我需要更改设置,如果不存在,我需要创建它。现在我有以下内容,但我觉得它很难看。我正在查看的结构有一个子元素列表,它们都具有相同的结构,所以不幸的是我不能只寻找特定的标签。

thing_structure = lxml.objectify(get_from_REST_service())
found_thing = False
if thing_structure.find('settings') is not None:
    for i, foo in enumerate(thing_structure.settings):
        if foo.is_what_I_want:
            modify(thing_structure.settings[i])
            found_thing = True
if not found_thing:
    new = lxml.etree.SubElement(thing_structure, 'setting')
    modify(new)

send_to_REST_service(thing_structure)

【问题讨论】:

    标签: python code-cleanup


    【解决方案1】:

    总体而言,结构还不错(假设您需要在设置中的 1+ 项上调用 modify -- 如果“只有一个”,即如果 is_what_I_want最多只能为一个设置设置标志,这当然是不同的,因为您可以并且应该使用for循环中的break——但这不是我从你的Q中得到的你意图的印象,如果我错了,请澄清!)。有一个冗余:

    for i, foo in enumerate(thing_structure.settings):
        if foo.is_what_I_want:
            modify(thing_structure.settings[i])
            found_thing = True
    

    拥有i 并使用它再次获得相同的foo 在这里没有用,因此您可以简化为:

    for foo in thing_structure.settings:
        if foo.is_what_I_want:
            modify(foo)
            found_thing = True
    

    如果您要重新绑定项目,您只需要索引,即执行诸如thing_structure.settings = whatever 之类的分配。 (顺便说一句,foo 以外的名称也不会受到伤害;-)。

    【讨论】:

    • foo 名称不是我在实际代码中使用的名称,我只是想稍微降低复杂性,而不是添加任何特定于我的代码库的东西——更多的是通用结构。事实上,我确实重新绑定了该项目,这就是我使用 i 的原因。
    • @Daenyth,foo 很明显(这就是为什么我在那里有一个笑脸的原因),但是删除项目重新绑定的关键不同操作是过于简单化了——它确实使所有的不同无论您是在做这种重新绑定(因此需要enumerate)还是不这样做(因此不需要它)。有了您的新信息,并且始终假设您需要能够调用 modify 一次 或多次 次(不仅仅是一次),我看不到任何实质性的简化(一些技巧,是的,但是它们可能会损害清晰度而不是增强清晰度)。
    • Alex,有机会可以看看这个:stackoverflow.com/questions/3826473/… 吗?谢谢
    【解决方案2】:

    我会这样写:

    thing_structure = lxml.objectify(get_from_REST_service())
    if thing_structure.find('settings') is not None:
        foos = [foo for foo in thing_structure.settings if foo.is_what_I_want]
            or [lxml.etree.SubElement(thing_structure, 'setting')]
        for foo in foos:
           modify(foo)
    send_to_REST_service(thing_structure)
    

    我不关心is not None 并尽可能消除它。这里有可能,我会写:

    if thing_structure.find('settings'):
    

    【讨论】:

      猜你喜欢
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 2017-08-15
      • 1970-01-01
      相关资源
      最近更新 更多