Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #101847
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: "x == None" vs "x is None" |
| Date | 2016-01-17 22:29 +1100 |
| Message-ID | <mailman.59.1453030200.15297.python-list@python.org> (permalink) |
| References | <n7fo7q$dso$1@news2.informatik.uni-stuttgart.de> <mailman.57.1453025729.15297.python-list@python.org> <n7fshb$f36$1@news2.informatik.uni-stuttgart.de> |
On Sun, Jan 17, 2016 at 10:05 PM, Ulli Horlacher
<framstag@rus.uni-stuttgart.de> wrote:
> Chris Angelico <rosuav@gmail.com> wrote:
>> On Sun, Jan 17, 2016 at 8:51 PM, Ulli Horlacher
>> <framstag@rus.uni-stuttgart.de> wrote:
>> > I have seen at several places "x == None" and "x is None" within
>> > if-statements.
>> > What is the difference?
>> > Which term should I prefer and why?
>>
>> tl;dr: Prefer "x is None" as a check.
>
> And for the negation?
> "if not x is None" or "if x is not None"
>
> I have seen the last one several times, but i do not understand it, because:
>
>>>> x=0
>>>> x is not None
> True
>>>> not None
> True
>>>> x is True
> False
There's no actual difference:
>>> dis.dis(lambda x: x is not None)
1 0 LOAD_FAST 0 (x)
3 LOAD_CONST 0 (None)
6 COMPARE_OP 9 (is not)
9 RETURN_VALUE
>>> dis.dis(lambda x: not x is None)
1 0 LOAD_FAST 0 (x)
3 LOAD_CONST 0 (None)
6 COMPARE_OP 9 (is not)
9 RETURN_VALUE
The compiler can tell that "not x is None" is exactly the same thing
as "x is not None". Personally, I'd rather spell it "is not None",
partly because it reads more like English that way, and partly because
one operator is better than two; but you're welcome to spell it "not x
is None" if that has other benefits (eg consistency).
ChrisA
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
"x == None" vs "x is None" Ulli Horlacher <framstag@rus.uni-stuttgart.de> - 2016-01-17 09:51 +0000
Re: "x == None" vs "x is None" Chris Angelico <rosuav@gmail.com> - 2016-01-17 21:15 +1100
Re: "x == None" vs "x is None" Ulli Horlacher <framstag@rus.uni-stuttgart.de> - 2016-01-17 11:05 +0000
Re: "x == None" vs "x is None" Peter Otten <__peter__@web.de> - 2016-01-17 12:26 +0100
Re: "x == None" vs "x is None" Chris Angelico <rosuav@gmail.com> - 2016-01-17 22:29 +1100
Re: "x == None" vs "x is None" <paul.hermeneutic@gmail.com> - 2016-01-17 11:01 -0700
Re: "x == None" vs "x is None" Random832 <random832@fastmail.com> - 2016-01-17 16:33 -0500
Re: "x == None" vs "x is None" Chris Angelico <rosuav@gmail.com> - 2016-01-18 08:38 +1100
Re: "x == None" vs "x is None" Ben Finney <ben+python@benfinney.id.au> - 2016-01-18 13:46 +1100
Re: "x == None" vs "x is None" fernando junior <fernandojr.ifcg@live.com> - 2016-01-19 14:20 -0800
csiph-web