Is there a Python 3+ equivalent to JavaScript double-equals (==)

twitter logo github logo ・1 min read

Ok, so I want a Python3 equivalent of JavaScript == operator.
WAIT! Before you say, "Just use Python ==", no,
that's by all means what I'm NOT looking for, I want a version
of == that will do type coercion etc... to see if two values are
SIMILAR, such as:

31 == "31" // true
31 === "31" // false


# roughly equal to JS ==
def eql(*args):
    vals = []
    for arg in args:
    lastval = vals[0]
    lasttrue = False
    for v in vals:
        lasttrue = v == lastval
    return lasttrue
eql(1,"1") # True
1 == "1" # False

Is there any kind of built in Python function or operator that acts like JS ==?

twitter logo DISCUSS (7)
markdown guide

How about this for a simple start. You would also need to check for falsy.

str(x) == str(y)


This wont really work great for dicts or classes that have not so great string conversion. But if you are OK with that limitation. You can combine this with sets + len.

def equals(*args):
    return len(set(str(x) for x in args)) == 1

You could maybe get better results with using hash instead of string but that will fail for mutable collections like dict or list.


It works, and I love it, but can you explain what it's doing more in depth, or link some learning sources, I've never used a set before, and now I feel ashamed of that...

A set is an unordered hashed sequence of distinct items. Meaning it has O(1) look up and contains only unique items. Duplicates are ignored. Therefore, if we create a set of strings that are all the same, our length will be one.

Python docs are here docs.python.org/3/tutorial/datastr...


No, I don't believe so.
As Python is a strongly typed language it doesn't, in general, implicitly cast values.
Also to quote the zen of python: "Explicit is better than implicit."

Classic DEV Post from Nov 1 '19

How I Got Hired at DEV (and Every Other Tech Job)

PDS OWNER CALIN (Calin Baenen) profile image
I am a 13 (as of Oct 30 of 2019) yr/o developer (I have been developing mini-projects for 4, years now, since I was 9), who makes projects in languages like: Java, HTML, Python 3, JS, CSS, and C#.

Thanks for visiting dev.to

A Beginner's Guide to dev.to