Argument Presence Checking via Identity or Boolean Operation?
Steven D'Aprano
steve at pearwood.info
Thu Jun 4 09:38:00 EDT 2015
On Thu, 4 Jun 2015 11:18 am, Russell Brennan wrote:
> I'm going to x-post this to stackoverflow but...
>
> When checking a method's arguments to see whether they were set, is it
> pythonic to do an identity check:
>
> def doThis(arg1, arg2=None):
> if arg2 is None:
> arg2 = myClass()
>
>
> Or is it proper form to use a short-circuiting boolean:
>
> def doThis(arg1, arg2=None):
> arg2 = arg2 or myClass()
Those two checks have different semantics, so the answer depends on what
behaviour you want.
Do you want *any* of None, 0, 0.0, [], (), {}, False, etc. to trigger the
myClass() behaviour? Then the right answer is to use a short-circuit
boolean. (And you probably should use False as the default for arg2.)
Do you want *only* None to trigger the myClass() behavious? Then the right
answer is to use the identity check.
--
Steven
More information about the Python-list
mailing list