python - Argument Presence Checking via Identity or Boolean Operation? -
when checking method's arguments see whether set, pythonic identity check:
def dothis(arg1, arg2=none): if arg2 none: arg2 = myclass()
or proper form use short-circuiting boolean:
def dothis(arg1, arg2=none): arg2 = arg2 or myclass()
in support of former, pep 8 states:
comparisons singletons none should done or not , never equality operators. also, beware of writing if x when mean if x not none -- e.g. when testing whether variable or argument defaults none set other value. other value might have type (such container) false in boolean context!
on other hand, google style guide:
use "implicit" false if @ possible. ...
but @ same time states...
never use == or != compare singletons none. use or not.
does apply "none" since evaluates false always, and/or boolean comparison equivalent ==/!= under hood?
edit: answer last question, "or" doesn't seem equivalent "==" under hood:
in [17]: timeit.timeit("1 or none", number=100000000) out[17]: 2.0310521125793457 in [18]: timeit.timeit("1 none", number=100000000) out[18]: 2.618263006210327 in [19]: timeit.timeit("1 == none", number=100000000) out[19]: 4.554893970489502
consider happen if arg2
equals "falsish" value such 0 (or empty string, list, tuple, dict or set -- name few).
arg2 = arg2 or myclass()
would set arg2
myclass()
though arg2=0
might have been intended value arg2
. always use is
determine if arg2
none.
Comments
Post a Comment