Argument Presence Checking via Identity or Boolean Operation?

Peter Otten __peter__ at web.de
Thu Jun 4 04:07:51 EDT 2015


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()

When I read this I always have to stop and consider whether there are valid 
falsey arguments that could be passed as arg2.

An obvious example is

def do_this(arg=None):
    arg = arg or []
    arg.append(42)

a = []
do_this(a)
do_this(a)
print(a) # expected: [42, 42] actual output: []

Choosing the first approach is not just a matter of style, it avoids a 
source of subtle bugs.




More information about the Python-list mailing list