Argument Presence Checking via Identity or Boolean Operation?

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Argument Presence Checking via Identity or Boolean Operation?

Steven D'Aprano-8
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