3 ms·
`is` is for identity whereas `=` is for equality. You rarely want `is` unless you're asking if two references are the same object. This is almost exclusively us
by orf 6y ago
`is` is for identity whereas `=` is for equality. You rarely want `is` unless you're asking if two references are the same object. This is almost exclusively used for `x is False/True`, but sometimes used to denote "missing" arguments (where true/false may be valid):
missing = object()
def func(a=missing):
if a is missing:
raise ValueError('you must pass a')
This "numbers less than 256 are the same objects" is a fairly common on the list of "wtf python" but I've never understood it. You don't use `is` like that and you would never use it in code because the operator you're using is not the right one for the thing you're trying to do.
Plus if this is the biggest wtf then that's pretty good going.
- cs702 6y agoYes, of course. BTW, that's not the "biggest" WTF feature; it's just my favorite. There's a long list of WTF features here: https://github.com/satwikkansal/wtfpython https://github.com/satwikkansal/wtfpython Otherwise, I agree, it's a pretty good going :-)
- baud147258 6y agoThe "numbers less than 256 are the same objects" reminds me of the existence of the IntegerCache in Java, with an array storing the number from -128 to 127.
- pansa2 6y agoYes, Python has an integer cache holding the values -5 to 256.
- mark-r 6y agoThe "numbers less than 256 are the same objects" wasn't done so you could use "is" on them, that's just a side effect. It was done as an optimization, because those small integers are far more common than the larger ones. You save space, because you need only one copy of those small integers. And you save time, because those objects are never destroyed or recreated.
- orf 6y agoYes, of course, But I never said that it was done so you could use “is” with them, only that “is” is the wrong thing to do on them.
- roelschroeven 6y agoOf course. "is" is almost always the wrong thing to do.