473,796 Members | 2,550 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

conventions/requirements for 'is' vs '==', 'not vs '!=', etc

I'm wondering what is the canonical usage of the keywords 'is' and
'not' when you're writing conditionals and loops. The one I've been
following is completely arbitrary--I use the symbols '==', '!=' for
numerical comparisons and the words 'is', 'not' for everything else.

Thanks in advance!
Jun 27 '08 #1
21 1013
On Mon, 19 May 2008 12:39:36 -0700, destroooooy wrote:
I'm wondering what is the canonical usage of the keywords 'is' and
'not' when you're writing conditionals and loops. The one I've been
following is completely arbitrary--I use the symbols '==', '!=' for
numerical comparisons and the words 'is', 'not' for everything else.
That's wrong. Use ``==`` and ``!=`` for testing equality/inequality and
``is`` and ``is not`` for identity testing. And testing for identity is
quite rare. Rule of thumb: Use it only for known singletons like `None`.

Ciao,
Marc 'BlackJack' Rintsch
Jun 27 '08 #2
On Monday 19 May 2008 03:39:36 pm destroooooy wrote:
I'm wondering what is the canonical usage of the keywords 'is' and
'not' when you're writing conditionals and loops. The one I've been
following is completely arbitrary--I use the symbols '==', '!=' for
numerical comparisons and the words 'is', 'not' for everything else.
It's not arbitrary, and you shouldn't be using that convention.

The question is really about "equality" versus "identity". Two identical sized
cubes may be equal, but they are certainly not the same cube. The main
concept here: identity [usually] implies equality, but equality almost never
implies identity (two objects that are equal may be distinct nonetheless).

More practical example, two angles with the same measure are equal by every
mathematical concept, but opposing angles on a parallelogram are not the same
one.

Sometimes, you need to test for equality, as in "is this user input equal
to '1'?". Sometimes, you need to test for identity "is this user input
this '1' that I have here?" (note: the second answer should be 'no', unless
that by some dark magic the user manages to get that same '1' that is in your
code).

The most common use case is equality. You test for equality with == and!=.
The darker case is identity. You test for identity with "is" and "is not".
Whenever you use "is", ask yourself a question: does a negative answer makes
sense if the objects are equal?

Personally, I like to use "is" with singletons. I find it easier to type and
read "if param is None" than "if param == None", but some python developers
dislike the first one because of the "dark magic" involved in knowing that
None is a singleton.

When in doubt, test for equality. Use "is" only when you are certain that you
know the difference. Python does some optimizations that may it seem like it
is working with 'is' at first, but it really isn't:

In: a="hi"
In: b="hi"
In: a is b
Out: True <-- dark magic here, python optimized the string storage,
In: a is "h"+"i" <-- by using the same object instead of creating a new one
Out: False <-- but even that won't always work, so


In: a="a very long string, at least longer than 'hi'"
In: b="a very long string, at least longer than 'hi'"
In: a is b
Out: False <-- never, never rely on magic.

I hope I was useful.

Cheers,

--
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
Jun 27 '08 #3
On 19 mai, 22:29, Luis Zarrabeitia <ky...@uh.cuwro te:
(snip)
The main
concept here: identity [usually] implies equality,
I really enjoyed the "usually" disclaimer !-)
Jun 27 '08 #4
Luis Zarrabeitia schrieb:
Personally, I like to use "is" with singletons. I find it easier to type and
read "if param is None" than "if param == None", but some python developers
dislike the first one because of the "dark magic" involved in knowing that
None is a singleton.
Testing for None is the only common case where you should *not* use ==
comparison. If you want to check if something is None then do "if
something is None". Easy, isn't it? :]

Look, what Python does for the various way (simplified):

"if a == None:" -"if a.__cmp__(None) "

"if a is None" -"if id(a) == id(None)"

"if a:" -"if a.__nonzero__() " / "if a.__len__()"

Christian

Jun 27 '08 #5
En Mon, 19 May 2008 17:58:48 -0300, br************* ****@gmail.com
<br************ *****@gmail.com escribió:
On 19 mai, 22:29, Luis Zarrabeitia <ky...@uh.cuwro te:
(snip)
>The main
concept here: identity [usually] implies equality,

I really enjoyed the "usually" disclaimer !-)
In some *rare* cases, identity does not imply equality:

pyinf = 1e300*1e300
pynan = inf-inf
pynan
-1.#IND
pynan is nan
True
pynan == nan
False

--
Gabriel Genellina

Jun 27 '08 #6
On May 20, 6:58 am, "bruno.desthuil li...@gmail.com "
<bruno.desthuil li...@gmail.com wrote:
On 19 mai, 22:29, Luis Zarrabeitia <ky...@uh.cuwro te:
(snip)
The main
concept here: identity [usually] implies equality,

I really enjoyed the "usually" disclaimer !-)
Well you have to be careful in case some smartarse comes back with a
class with something like this in it:

def __eq__ (self, other) :
if self is other : return False

%)
Jun 27 '08 #7
i am confused.

x=5
y=5

x==y -True
x is y -True

shouldnt x is y return False since they shouldnt(dont?) point to the
same place in memory, they just store an equal value?

Jun 27 '08 #8
On Mon, 19 May 2008 20:34:22 -0700 (PDT)
no**********@ya hoo.se wrote:
i am confused.

x=5
y=5

x==y -True
x is y -True

shouldnt x is y return False since they shouldnt(dont?) point to the
same place in memory, they just store an equal value?
For some immutable values (such as numbers and strings), Python will have separate variables reference the same object, as an optimization. This doesn't affect anything, since the numbers are immutable anyway and a shared reference won't create any unexpected changes.

It also works with small, but not large, strings:
>>x = 'hello'
y = 'hello'
x == y
True
>>x is y
True
>>a = 'this is longer'
b = 'this is longer'
a == b
True
>>a is b
False
>>>
In the above example, Python has created only one string called 'hello' and both x and y reference it. However, 'this is longer' is two completely different objects.
Jun 27 '08 #9
no**********@ya hoo.se a écrit :
i am confused.

x=5
y=5

x==y -True
x is y -True

shouldnt x is y return False since they shouldnt(dont?) point to the
same place in memory, they just store an equal value?
Python's "variable" do not "store values", they are name to object
bindings. x = 5 is a shortand for globals()['x'] = int(5), which means
"create an int instance with value 5 and bind it to the name 'x' in the
global namespace'. wrt/ the identity test yielding true, it's the result
of a CPython specific optimisation for small integer objects, that are
cached and reused. Since Python integers are immutable, they can safely
be shared. Now since it's an implementation specific thing, you should
by no mean rely on it.

Jun 27 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2965
by: Muthu | last post by:
I've read calling conventions to be the order(reverse or forward) in which the parameters are being read & understood by compilers. For ex. the following function. int Add(int p1, int p2, int p3); The parameters here can be read either in the forward order from p1 till p3 or reverse order from p3 till p1. Can anyone explain what is the advantage/disadvantage of either of
7
2485
by: cmiddlebrook | last post by:
Hi there, I keep finding myself getting inconsistent with naming conventions for things like member variables, class names etc and I just want to find something that suits me and stick to it. I am wondering if there are any naming conventions around that are deemed suitable by the general C++ community. I have googled around and I can't find much - mostly long lists of hungarian-like prefixes which is not really what I'm after.
1
6551
by: clintonG | last post by:
Does the use of DTD, XML Schema and similar constructs adopt the use of C# naming conventions? If so how do I make the distinction of how to apply C# conventions with XML elements, attributes and so on? Any referrals to resources that discuss or document XML Naming Conventions? -- <%= Clinton Gallagher, "Twice the Results -- Half the Cost" Architectural & e-Business Consulting -- Software Development NET...
7
2570
by: Ralph Lund | last post by:
Hi. I am starting a new project with C#. I am searching for "good" coding conventions. I know that there are some coding conventions from microsoft, (but they are very extensive and not clear). In the example programs of Microsoft they use different coding conventions: private members sometimes with underscore, sometimes without; when calling a method sometimes: method(param1, param2) or method ( param1, param2) (with or without...
3
4353
by: clintonG | last post by:
Does the use of DTD, XML Schema and similar constructs adopt the use of C# naming conventions? If so how do I make the distinction of how to apply C# conventions with XML elements, attributes and so on? Any referrals to resources that discuss or document XML Naming Conventions? -- <%= Clinton Gallagher, "Twice the Results -- Half the Cost" Architectural & e-Business Consulting -- Software Development NET...
5
6177
by: rastaman | last post by:
Hi all, I know of the existence of Object Naming Conventions for Visual Basic 6. Now I'm reading some books about VB .NET, but the names used for the objects are button1, picturebox1, etc. I wonder if I can use the same naming conventions as for VB6 ? If so, what about the names for the new objects in .NET. Kind regards rastaman
4
5451
by: Patrick | last post by:
what are the general naming conventions for vb.net controls. esp txtUserName, lblPassword, btnSubmit What are the prefixes for the controls???? I've tried to search hi and low on the net, but in vain. I'd much appreciate it if someone could guide me with regards to this. All i need are standards for me to follow by my self. Cuz i'm finding it difficult to make my own darn standards.
18
3288
by: psbasha | last post by:
Hi, I would like to know what naming conventions we can follow for the following types of variables/sequences : Variables : ------------- Integer Float Boolean
10
3267
by: sulekhasweety | last post by:
Hi, the following is the definition for calling convention ,which I have seen in a text book, can anyone give a more detailed explanation in terms of ANSI - C "the requirements that a programming system places on how a procedure is called and how data is passed between a calling program and procedures are called calling conventions"
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9531
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10237
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10187
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10018
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7553
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6795
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4120
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2928
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.