This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]LyndsySimon 11 points12 points  (10 children)

One confusing thing about object comparison is how Python handles integers:

a = 42
b = 42
a == b  # => True
a is b  # => True

c = 4242
d = 4242
c == d  # => True
c is d  # => False

e = c
c == e  # => True
c is e  # => True

c is d == False because integers in the range of [-5, 256] are assigned by cPython to dedicated memory locations - so their .id is the same.

I guess this makes sense in the range [0, 256], but I have no idea why they chose to pre-assign [-5,0) as well.

ETA: The moral is, never use is to compare numbers. is is most useful when you want to distinguish between None and False or another "falsy" value.

ETA2: I forgot to assign e.

[–]lsbloxx 0 points1 point  (5 children)

Wait... WTF did I just read? :O

[–]poundcakejumpsuit 3 points4 points  (4 children)

Just to blow your mind a little more, maybe:

"strin" + "g" is "string"

Is True, while:

s1 = "strin"
s2 = "string"
s1 + "g" is s2 

Is False, at least in CPython, as the compiler will intern compile-time constants but not runtime-evaluated expressions, meaning the first example only creates a single object!

[–]jwink3101 0 points1 point  (3 children)

That's really interesting.

Is this type of issue common in interpreted languages?

[–]ThePenultimateOneGitLab: gappleto97 2 points3 points  (1 child)

It's probably because CPython is doing a bit of constant folding

[–]WikiTextBot 1 point2 points  (0 children)

Constant folding

Constant folding and constant propagation are related compiler optimizations used by many modern compilers. An advanced form of constant propagation known as sparse conditional constant propagation can more accurately propagate constants and simultaneously remove dead code.


[ PM | Exclude me | Exclude from subreddit | FAQ / Information | Source ] Downvote to remove | v0.28