alphanumeric
alphanumeric

Reputation: 19329

Python: If Multiple Nones of Falses

While working with multiple conditions I am currently using following syntax:

if hasattr(myClass,methodA)==False or hasattr(myClass,methodB)==False or hasattr(myClass,methodC)==False: return

I wonder if there is a shorter way of doing the same. What I don't like particularly is that I have to use "==False" three times in repetition. Would it be correct if used this instead:

if not hasattr(myClass,methodA) or not hasattr(myClass,methodB) or not hasattr(myClass,methodC): return

Upvotes: 1

Views: 83

Answers (2)

BrenBarn
BrenBarn

Reputation: 251355

You can do if not all(hasattr(myClass,meth) for meth in ('methodA', 'methodB', 'methodC'))

Upvotes: 4

jdotjdot
jdotjdot

Reputation: 17042

Functionally:

if any(map(lambda method: not hasattr(myClass, method), ['methodA', 'methodB', 'methodC'])):

Upvotes: 0

Related Questions