Pythonic way to check if something exists?

后端 未结 6 1408
北恋
北恋 2020-12-12 14:06

This is pretty basic but I was coding and started wondering if there was a pythonic way to check if something does not exist. Here\'s how I do it if its true:



        
6条回答
  •  失恋的感觉
    2020-12-12 14:09

    LBYL style, "look before you leap":

    var_exists = 'var' in locals() or 'var' in globals()
    

    EAFP style, "easier to ask forgiveness than permission":

    try:
        var
    except NameError:
        var_exists = False
    else:
        var_exists = True
    

    Prefer the second style (EAFP) when coding in Python, because it is generally more reliable.

提交回复
热议问题