【问题标题】:Python NOOP replacement [duplicate]Python NOOP替换[重复]
【发布时间】:2012-09-10 13:59:32
【问题描述】:

我经常需要临时注释一些代码,但是有像下面这样的情况,注释一行代码会出现语法错误

if state == False:
    print "Here I'm not good do stuff"
else:
#    print "I am good here but stuff might be needed to implement"

有没有什么东西可以作为 NOOP 来保持这种语法正确?

【问题讨论】:

    标签: python python-2.7 comments noop


    【解决方案1】:

    我发现,如果您将代码放在三引号注释 '''comment''' 中,它的行为就像一个 NOOP,所以您可以放置​​一个三重引号注释,以防代码被删除或使用 # 注释时充当 NOOP .

    对于上述情况:

    if state == False:
        '''this comment act as NOP'''
        print "Here I'm not good do stuff"
    else:
        '''this comment act as NOP and also leaves the 
        else branch visible for future implementation say a report or something'''
    #    print "I am good here but stuff might be needed to implement" 
    

    【讨论】:

    • 你应该使用pass (docs.python.org/reference/simple_stmts.html#pass) 作为noop。这样做的优点是简短且没有其他含义(字符串可能会被程序以不需要的方式解释)。
    • @Nobody 你有不想要的行为的例子来知道应该避免什么吗?
    • 裸字符串应该没问题,但您必须小心不要将文档测试写入这些字符串(如果不需要的话)。除此之外,还有对冗长字符串的不必要解析,它们将被评估并返回以被忽略(也许这将被优化掉)。我不能想出更多不太可能的极端案例,但pass 是要走的路,因为它是为这种情况而设计的。如果你以这种方式使用 cmets,你就打破了 cmets 的规则:它们可以在不改变程序语义的情况下被删除。
    • 同意。你也可以做1+1,比如说——关键是pass已经意味着“什么都不做”,这样阅读代码的其他人就会明白它什么都不做。
    • 多行字符串可以用作cmets和they generate no code。此外,只要这些字符串没有放在defclass 之后或模块的开头,因此不是文档字符串,doctest ignores these strings
    【解决方案2】:

    您要查找的操作是pass。所以在你的例子中它看起来像这样:

    if state == False:
        print "Here I'm not good do stuff"
    else:
        pass
    #    print "I am good here but stuff might be needed to implement"
    

    您可以在此处阅读更多信息: http://docs.python.org/py3k/reference/simple_stmts.html#pass

    【讨论】:

      【解决方案3】:

      在 Python 3 中,... 可以很好地替代 pass

      class X:
          ...
      
      def x():
          ...
      
      if x:
          ...
      

      我将其读作“待完成”,而pass 的意思是“此页面故意留白”。

      它实际上只是一个字面量,很像 NoneTrueFalse,但它们的优化都是一样的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-11
        • 1970-01-01
        • 2019-05-15
        • 1970-01-01
        • 2016-06-06
        • 1970-01-01
        • 1970-01-01
        • 2019-09-30
        相关资源
        最近更新 更多