Python: Why doesn't equality comparing int with string give an error?

In Python 3, an attempt to arrange the string and int (for example, 1 > "1" ) throws a TypeError. Why doesn't string comparison with int for equality cause an error? (for example, 1=="1" ) What is an example when comparing a string with an int makes sense? Why is JavaScript and SQL taking a different approach?

RELATED: How does Python compare string and int?

+6
source share
3 answers

This allows you, for example, to have a dictionary with keys of mixed types.

If you could not compare 1 and "1" for equality, you cannot use them as keys in one dictionary.

Be that as it may, you can compare them, and they always compare unequal ones :

Objects must not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types are always compared unevenly and ordered sequentially, but arbitrarily.

+5
source

The reason that orderings raise a TypeError on disparate objects is to imagine that there is no reasonable answer, and not any prediction about whether it will ever be useful. This check allows a check of equality, since there is an answer to the question, are two disparate objects equal? (They are not here). See, for example, http://www.gossamer-threads.com/lists/python/dev/919516 .

+5
source

Strength and weakness of a set of languages

Typing can be strong or weak (weakened). The stronger the input language, the fewer operations can be used in the same operation. The weakness and strength of a language set does not have an exact threshold - a language may have a stronger set than another, and weaker than another. Writing Python is much stronger than JS .

== implemented as a less or less typed operation. It can compare different types, but you need to have both values โ€‹โ€‹of the same type in order to be able to get True . a == b #true means a , and b are objects of the same type and have equal values. > < in Python 3 it is implemented as a strongly typed operation and cannot be performed for different types.

0
source

Source: https://habr.com/ru/post/915903/


All Articles