15

How do I achieve the effect of the === operator in Python?

For example, I don't want False == 0 to be True.

Rob W
  • 341,306
  • 83
  • 791
  • 678
speg
  • 1,959
  • 6
  • 24
  • 34

4 Answers4

41

If you want to check that the value and type are the same use:

x == y and type(x) == type(y)

In Python, explicit type comparisons like this are usually avoided, but because booleans are a subclass of integers it's the only choice here.


x is y compares identity—whether two names refer to the same object in memory. The Python boolean values are singletons so this will work when comparing them, but won't work for most types.

Jeremy
  • 1
  • 85
  • 340
  • 366
  • 6
    Righto. This is the right answer. That green check needs to move. – Ian McLaird Jul 17 '11 at 18:05
  • 2
    `True, False == 1,0` is part of the language spec, so which Python implementation does not do it? Before you write `type(x) == type(y)` switch to a language that does not use duck typing. – Jochen Ritzel Jul 17 '11 at 18:14
  • @Jeremy Bank: `id(True) == id(True)` is part of the spec as well: "The two objects representing the values False and True are the only Boolean objects.". – Jochen Ritzel Jul 17 '11 at 18:21
16

Try variable is False. False is 0 returns False,

g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
  • 6
    Not a good answer -- it won't necessarily work with other values. – Ethan Furman Sep 13 '11 at 02:14
  • @Ethan et al - the OP needs to move the check if he'd like, but I can't remove the post w/o him deselecting it as the answer. It did what he needed at the time though - perhaps he doesn't need explicit type comparison. – g.d.d.c Sep 13 '11 at 03:43
  • @Ethan Furman: why not? `is` in python tests object identity, which - as the tags "python", "comparison", "identity" seem to indicate - is exactly what the OP was after. Or am I missing something? – Steven Sep 13 '11 at 10:24
  • 5
    @Steven, The OP 1) did not explain exactly what he was after, and 2) did not add those tags. So we can't be sure what, exactly, he wants. But if it is the Mathematica meaning, then it is not identity, but type and value. Consequently, `a = 98273; b=98273; a === b` -> should be `True` but `is` will say it's `False`. – Ethan Furman Sep 13 '11 at 13:19
2

Going with the Mathematica definition, here's a small function to do the job. Season delta to taste:

def SameQ(pram1, pram2, delta=0.0000001):
    if type(pram1) == type(pram2):
        if pram1 == pram2:
            return True
        try:
            if abs(pram1 - pram2) <= delta:
                return True
        except Exception:
            pass
    return False
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • Is it really supposed to be `abs(pram1) - abs(pram2) <= delta`? It seems like `abs(pram1 - pram2) <= delta` makes more sense. – Jeremy Sep 20 '11 at 02:52
1

You can use the is operator to check for object identity. False is 0 will return False then.

Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122