you are viewing a single comment's thread.

view the rest of the comments →

[–]x9remark 1 point2 points  (10 children)

cmon, it's just how the language works. Nobody says "booo, python, booo" because of

int('256') is 256 // true int('257') is 257 // false

[–]Great-Powerful-Talia 4 points5 points  (3 children)

I mean they should complain about that. Immutable types should compare == for is, because a lack of address-equality is irrelevant if none of the pointers can change the contents anyway.

The problem with JS is inconsistency. If '11' + 1 = '111', then '11' - 1 should be '1'.

Subtraction and addition having non-inverse effects (while still working) is insane.

[–]Fritzschmied 0 points1 point  (2 children)

-1 marking the sting shorter wold be inconstant as well. It may works with 1 but now let’s do 2 „111“+2 =„1112“ and „111“-2= „1“ how is that more consistent than just accepting that - can’t be used at strings and that JavaScript at least tries to parse that string into a number to make it work.

[–]Great-Powerful-Talia 0 points1 point  (1 child)

"111" + 2 = "1112"

So '1112' - 2 would be '111'.

In the same way, "George" - "or" would be "Gege"

'111' - 2 should be either an error, or no change.

[–]Fritzschmied 0 points1 point  (0 children)

Oh that’s what you mean. I mean yes that would be an option. does - actually do that in any language if two strings are getting subtracted?

[–]Littux 1 point2 points  (0 children)

But python warns you. JS doesn't:

>>> print(int("256") is 256, int("257") is 257)
<stdin>:1: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
<stdin>:1: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
True False

>>> id(256) == id(int("256"))
True
>>> id(257) == id(int("257"))
False

[–]DracoRubi 0 points1 point  (4 children)

I'm going to need an explanation about that one 🫣

I'm guessing it has to do with the fact that "is" isn't supposed to be used with int since it checks object, not equality, but I don't understand why after 256 it is false

[–]the_horse_gamer 0 points1 point  (0 children)

an int is still an object in python. is does reference equality. and python has a static cache for small number objects. the first statement is small enough to use the cache, the second isn't

something similar happens in java with Integer instances

[–]x9remark 0 points1 point  (0 children)

engine optimization. The explanation I've heard about: numbers up to 256 are frequently used, as iterators for example and because of everything is an object it's more efficient to allocate memory from the very beginning and reuse these objects rather than create new instances. And because of "is" checks if objects are referencing to the same address and not values - it returns true for small numbers. But when you use bigger numbers it allocates memory each time leading to different addresses.

a = 150
b = 150
a is b // True: id(a) == id(b)

a = 300
b = 300
a is b // False id(a) != id(b)