Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #92039

Re: Argument Presence Checking via Identity or Boolean Operation?

From Peter Otten <__peter__@web.de>
Subject Re: Argument Presence Checking via Identity or Boolean Operation?
Date 2015-06-04 10:07 +0200
Organization None
References <CAAKgPaGY_4yB7z=R-UO=s5TEWwEXZsE1nSEXw00sQPMfH_Xt2g@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.152.1433405311.13271.python-list@python.org> (permalink)

Show all headers | View raw


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.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Argument Presence Checking via Identity or Boolean Operation? Peter Otten <__peter__@web.de> - 2015-06-04 10:07 +0200

csiph-web