What's a standard way to do a no-op in python?

后端 未结 3 932
清酒与你
清酒与你 2020-12-23 23:57

I often find myself writing if / elif / else constructs in python, and I want to include options which can occur, but for which the corresponding action is to do nothing. I

相关标签:
3条回答
  • 2020-12-24 00:28

    How about pass?

    0 讨论(0)
  • 2020-12-24 00:36

    Use pass for no-op:

    if x == 0:
      pass
    else:
      print "x not equal 0"
    

    And here's another example:

    def f():
      pass
    

    Or:

    class c:
      pass
    
    0 讨论(0)
  • 2020-12-24 00:37

    If you need a function that behaves as a nop, try

    nop = lambda *a, **k: None
    nop()
    

    Sometimes I do stuff like this when I'm making dependencies optional:

    try:
        import foo
        bar=foo.bar
        baz=foo.baz
    except:
        bar=nop
        baz=nop
    
    # Doesn't break when foo is missing:
    bar()
    baz()
    
    0 讨论(0)
提交回复
热议问题