Argument Presence Checking via Identity or Boolean Operation?
Ben Finney
ben+python at benfinney.id.au
Thu Jun 4 03:39:56 EDT 2015
Russell Brennan <RussellJBrennan at 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
More information about the Python-list
mailing list