Hacker News new | ask | show | jobs
by kbp 2485 days ago
I don't think that's a great example for Python; that's just knowing what "is" is for. The fact that it works the same as == for small integers in CPython is an optimisation showing through, but only in a place where it doesn't really matter.

You still need to have a grasp on the difference between reference equality and value equality without getting into anything anyone would call tricks or implementation details (eg, after `x = []; y = []; x.append(1)`, how many elements does y have?).

2 comments

>I don't think that's a great example for Python; that's just knowing what "is" is for. The fact that it works the same as == for small integers in CPython is an optimisation showing through, but only in a place where it doesn't really matter.

Python should have prevented checking primitives with is though -- only let object pointers...

I believe they're still object pointers in CPython, they're just ordinary singletons; in other implementations, they aren't even singletons. Python's object model doesn't have primitives. Adding special rules around them would significantly complicate the language as well as limit the implementors' ability to fiddle with the ranges of pre-allocated instances, for minimal benefit.
>in other implementations, they aren't even singletons

That would have been less surprising (since for < 256 the singleton-ness means all same valued instances have the same "address" (id), so behave in equality check as if they were plain numbers).

Integers are object pointers, too. CPython just so happens to preallocate a range of small integers[0].

[0]: https://github.com/python/cpython/blob/master/Objects/longob...

x=x.append(1) and guess what, now x is "None", yes it makes perfect sense for those who coded python for a while, but it's a disaster for newcomers.

too many similar demos

by the way I actually like python and use it often, just saying it can surprise you when you start, not intuitive per se until you become good at it.

Sure, x.append doesn't return a value. So x=x.append is None. You learn that one pretty quick.

Perhaps use x = x + [1] instead?

But yeah, surprises like this (unexpected return values) are actually a pretty strong case for using a language like Rust or C++ where the compiler will tell you this before you run the program.

x=1; id(x); x+=1; id(x); # different id, means x points to new location

x=[1,2],id(x), x+=[3], id(x) ; # same id, means x stay at the original location

there should be a blog page to list those surprises for beginners :)

>> yes it makes perfect sense for those who coded python for a while, but it's a disaster for newcomers.

It’s a disaster for newcomers to programming in general. I am pretty sure a seasoned developer in any other language would understand why that returns None, too.