I noted this syntax listed as a gotchya but with no explanation as to why:
def func(x=None):
#good
if x == None:
x = []
#bad
x = x or []
In what ways can this be a gotchya?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In this particular case, it’s bad because an empty list evaluates to false. If you mutate the list, then the results won’t be as expected
Since you want to check to see if the caller passed
Noneor not, you should just say that explicitly and not try to be clever. Objects like[],(),{},0, andFalseevaluate to false, as can any user-defined object that wants to — checking for falsehood really catches too many false positives.(Also: Using
is Noneinstead of== Nonecan be faster and more reliable.)