Difference between 'is' and '=='
fredrik at pythonware.com
Wed Mar 29 11:41:46 CEST 2006
Joel Hedlund wrote:
> For me, this means several things, and I'd really like to hear people's
> thoughts about them.
> It basically boils down to "don't ever use 'is' unless pushed into a corner,
> and nevermind what PEP8 says about it".
> Identity checks can only be done safely to compare a variable to a defined
> builtin singleton such as None.
> You cannot expect to ever have identity between a value returned by a
> function/method and a CONSTANT defined in the same package/module, if you do
> not have comlete control over that module.
or if the documentation guarantees that you can use "is" (e.g. by specifying
that you get back the object you passed in, or by specifying that a certain
object is a singleton, etc).
> Therefore, such identity checks should always be given a value equality
if the documentation guarantees that you can use "is", you don't need any
"value equality fallback".
> My conlusion is then that using 'is' is a bad habit and leads to less readable
> code. You should never use it, unless it leads to a *measurable* gain in
> performance, in which it should also be given a value equality fallback and a
> comment. And lastly, PEP8 should be changed to reflect this.
> Wow... that got a bit long and I applaud you for getting this far! :-) Thanks
> for taking the time to read it.
> So what are your thoughts about this, then?
you need to spend more time relaxing, and less time making up arbitrary
rules for others to follow.
read the PEP and the documentation. use "is" when you want object identity,
and you're sure it's the right thing to do. don't use it when you're not sure.
any other approach would be unpythonic.
More information about the Python-list