Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

like image 652
speg Avatar asked Jul 17 '11 17:07

speg


2 Answers

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.

like image 187
Jeremy Avatar answered Oct 10 '22 01:10

Jeremy


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
like image 31
Ethan Furman Avatar answered Oct 10 '22 01:10

Ethan Furman