Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strict comparison

In javascript, there are strict comparison operators op1 === op2 and op1 !== op2 that will compare both type and value. Is there a pythonic way of achieving the same thing?

So far I've only been able to come up with the following messy conditionals:

isinstance(op1, type(op2)) and isinstance(op2, type(op1)) and op1 == op2

and

not isinstance(op1, type(op2)) or not isinstance(op2, type(op1)) or op1 != op2
like image 968
Gillespie Avatar asked Jan 19 '15 21:01

Gillespie


People also ask

What does strict equality mean?

The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.

What does === mean in TS?

Equality Operators. Ternary/Conditional Operators. The Typescript has two operators for checking equality. One is == (equality operator or loose equality operator) and the other one is === (strict equality operator). Both of these operators check the value of operands for equality.

Should I use == or ===?

== in JavaScript is used for comparing two variables, but it ignores the datatype of variable. === is used for comparing two variables, but this operator also checks datatype and compares two values. Checks the equality of two operands without considering their type. Compares equality of two operands with their types.

What is === in react?

The triple equals ( === ) is used for strict equality checking it means both operands should be same type and value then only it returns true otherwise it returns false . Example: 1 === "1" // false.


1 Answers

Your approach would indeed check both value and type. There isn't a different operator in Python.

This having been said, in many cases that's not what you want - in Python's philosophy any object that behaves as a duck should be treated as a duck. You often don't want only dictionaries, you want "mapping-like" objects and so on - as long as the object can be used for the particular task then the code should accept it.

like image 126
Simeon Visser Avatar answered Sep 19 '22 22:09

Simeon Visser