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


Groups > comp.lang.python > #92038

Re: Argument Presence Checking via Identity or Boolean Operation?

From Ben Finney <ben+python@benfinney.id.au>
Subject Re: Argument Presence Checking via Identity or Boolean Operation?
Date 2015-06-04 17:39 +1000
References <CAAKgPaGY_4yB7z=R-UO=s5TEWwEXZsE1nSEXw00sQPMfH_Xt2g@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.151.1433403620.13271.python-list@python.org> (permalink)

Show all headers | View raw


Russell Brennan <RussellJBrennan@gmail.com> writes:

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

That is the Pythonic way to test whether an argument was set.

> In support of the former, PEP 8 states:
>
> Comparisons to singletons like None should always be done with is or
> is not , never the equality operators. Also, beware of writing if x
> when you really mean if x is not None -- e.g. when testing whether a
> variable or argument that defaults to None was set to some other
> value. The other value might have a type (such as a container) that
> could be false in a boolean context!

Yes. That's good advice.

> On the other hand, from the Google style guide:
>
> Use the "implicit" false if at all possible. ...

That's an over-statement. I'd say it is a bug in the document; “if not
otherwise contradicted by the style guide” is better.

What they are likely warning against is code like this::

    if foo is False:
        # …

which should instead be written::

    if not foo:
        # …

If the guide is not explicit about that, it should be.

> But at the same time states...
>
> Never use == or != to compare singletons like None. Use is or is not.
>
>
> Does this apply to "None" since it evaluates to False always, and/or is a
> boolean comparison equivalent to ==/!= under the hood?

No, it applies to None because it is a singleton and designed to be a
sentinel value.

-- 
 \         “A fine is a tax for doing wrong. A tax is a fine for doing |
  `\                                                 well.” —anonymous |
_o__)                                                                  |
Ben Finney

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


Thread

Re: Argument Presence Checking via Identity or Boolean Operation? Ben Finney <ben+python@benfinney.id.au> - 2015-06-04 17:39 +1000

csiph-web