What is the most pythonic way to check if multiple variables are not None?

后端 未结 5 1606
名媛妹妹
名媛妹妹 2021-01-30 19:48

If I have a construct like this:

def foo():
    a=None
    b=None
    c=None

    #...loop over a config file or command line options...

    if a is not None an         


        
5条回答
  •  情深已故
    2021-01-30 20:01

    It can be done much simpler, really

    if None not in (a, b, c, d):
        pass
    

    UPDATE:

    As slashCoder has correctly remarked, the code above implicitly does a == None, b == None, etc. This practice is frowned upon. The equality operator can be overloaded and not None can become equal to None. You may say that it never happens. Well it does not, until it does. So, to be on the safe side, if you want to check that none of the objects are None you may use this approach

    if not [x for x in (a, b, c, d) if x is None]:
        pass
    

    It is a bit slower and less expressive, but it is still rather fast and short.

提交回复
热议问题