Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #92040
| From | "Frank Millman" <frank@chagford.com> |
|---|---|
| Subject | Re: Argument Presence Checking via Identity or Boolean Operation? |
| Date | 2015-06-04 10:34 +0200 |
| References | <CAAKgPaGY_4yB7z=R-UO=s5TEWwEXZsE1nSEXw00sQPMfH_Xt2g@mail.gmail.com> <mkp10p$n0l$1@ger.gmane.org> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.153.1433406882.13271.python-list@python.org> (permalink) |
"Peter Otten" <__peter__@web.de> wrote in message
news:mkp10p$n0l$1@ger.gmane.org...
> 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.
>
I have a slight variation in that I want to keep a reference to the
argument -
def __init__(self, arg=None):
self.arg = arg or []
Based on your comment, I have changed it to -
def __init__(self, arg=None):
self.arg = [] if arg is None else arg
Does this pass your 'stop and consider' test?
Frank Millman
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Argument Presence Checking via Identity or Boolean Operation? "Frank Millman" <frank@chagford.com> - 2015-06-04 10:34 +0200
csiph-web