367 points · by luu · 9y ago · 146 comments
Plugging my near useless Python library that does this and a lot of other subtle, annoying things to break programs. The library is essentially a display of how much Python actually exposes to the user and how modifiable it is.
>>> from exterminate import AltPrint
>>> print("Hey! How are you?")
Yo dawwwwg! Wuz crackalackin' yo?
... because that string is not calculated locally, but retrieved via HTTP from an API call. So everything you print is sent to an external server.AltPrint calls Gizoogle.translate():
https://github.com/adtac/exterminate/blob/f18862ed5b2e143e18...
And Gizoogle.translate() performs an HTTP call:
https://github.com/adtac/exterminate/blob/f18862ed5b2e143e18...
For example, the first output of the following program is 4, but the second is still 7.
program main
integer m,n
m = 7
call corrupt(m)
write (*,*) m
n = 7
write (*,*) n
stop
end program main
subroutine corrupt (a)
integer a
a = 4
return
end call corrupt(7)
which causes a segfault for me. I suppose if you were using a compiler/platform that didn't store constants in read only memory, this might actually work.It is just a bad idea to implement the '==' operator using comparison on addresses instead of on values and I consider languages pretty low-level that do that.
In a sane language == is always a function adhering the attributes of an equivalence relation (reflexivity, symmetry and transivity), where a user can expect an actual value comparison - AFAIK one is advised to overwrite `equals` in e.g. Java, but I do not think this is good design.
//edit:
There is no obvious answer, as one could argue, that languages just use different names for the same concepts ('==' vs 'equals') and consider comparison by value or by reference more fundamental (and choose '==' for that).
Apparently it is too hard to move python proper over to that method because of backwards compatibility issues with C extensions.
> The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)
does anyone have any idea how they chose that range? it's a 262-wide block starting at -5, which seems incredibly arbitrary.
* Initial commit with -1...99 cached:
https://github.com/python/cpython/commit/842d2ccdcd540399501...
* Cache more negative numbers, -5...99:
https://github.com/python/cpython/commit/c91ed400e053dc9f11d...
https://bugs.python.org/issue561244
* Cache more positive numbers, -5...256:
https://github.com/python/cpython/commit/418a1ef0895e826c65d...
it looks like they searched the standard library for negative integer literals and that's how they settled on -5 for the low end.
the high end came after introducing the `bytes` object. it went up to 256 instead of just 255 for size/len checks.
> [...]
> It looks like there is a table of tiny integers and each integer is takes up 32 bytes.
It is the memory address but it's a "CPython implementation detail: This [return value of the id() function] is the address of the object in memory."[1]
Though you cannot use this to determine the size of an object, or rather you "shouldn't" because that assumes a very specific implementation detail, which isn't there.
If you'd like to get the size of an object, use sys.getsizeof().[2] Also keep in mind that containers in Python does not contain the objects themselves but references to them so the returned size is the size of the object itself only, non-recursively. Read "Is Python call-by-value or call-by-reference? Neither."[3] for some more details.
[1]: https://docs.python.org/3.6/library/functions.html#id
[2]: http://docs.python.org/3.6/library/sys.html#sys.getsizeof
[3]: https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-...
BTW, I didn't like the way the difference between mutable and immutable objects was pointed out, it sounded like the language recognized and supported those two types, when in fact the difference is just in the methods exposed by the objects. Even immutable objects can be modified if you don't respect the contracts (like in the case of this article).
— Robert Anton Wilson, The Historical Illuminatus Chronicles, as spoken by Sigismundo Celine.
https://en.wikipedia.org/wiki/E-Prime
Kellogg and Bourland describe misuse of the verb to be as creating a "deity mode of speech", allowing "even the most ignorant to transform their opinions magically into god-like pronouncements on the nature of things".
Bourland and other advocates also suggest that use of E-Prime leads to a less dogmatic style of language that reduces the possibility of misunderstanding or conflict.
Alfred Korzybski justified the expression he coined — "the map is not the territory" — by saying that "the denial of identification (as in 'is not') has opposite neuro-linguistic effects on the brain from the assertion of identity (as in 'is')."
I suspect that with dependent types, nominal types are actually a degenerate type of dependent structural type: a dependent pair of a type and a proof that a string 'name' field has some particular value, or that a list<string> 'implements' field contains some particular string (the interface name).
Python is fine with duck typing.
a = 2**62 - 1
b = 2**62 - 1
a.object_id == b.object_id # true
a = 2**62
b = 2**62
a.object_id == b.object_id # false
Ruby does automatic promotion from Fixnum (native size) to Bignum (arbitrarily large) and uses one bit of the native size as a flag to identify this which is why 2^62 - 1 is the max instead of 2^63 - 1. Though I think this is only true of MRI and other implementations handle it without the flag bit.Perhaps one difference from Python is that in MRI Ruby Fixnum doesn't really even allocate an 'object', the object_id is the value in disguise. In fact all 'real' objects have even object_ids and all odd object_ids are integers:
a = 123456789
(a.object_id - 1) / 2 # 123456789It caches small integers, but also literals used in the same interpreter context (I'm probably getting that last term wrong). You'll get different results if you run these in from the shell as opposed to executing a script, try it out!
Here's a fun example
>>> x = 256; x is 256
True
>>> x = 257; x is 257
True
>>> x = 257
>>> x is 257
False
>>> def wat():
... x = 500
... return x is 500
>>> wat()
True >>> def f():
... x = 2222; y=2222
... return x is y
...
>>> f()
True
>>> f.func_code.co_consts
(None, 2222)
This last line is showing the constant pool, which is just a standard Python tuple.I believe the REPL compiles each input in a new toplevel module context, so each input gets its own constant pool.
Functions get their own constant pools, which explains the following behavior:
>>> if True:
... def f():return 2222
... def g():return 2222
...
>>> f() is g()
False >>> 100 is 100
True
>>> (10 ** 2) is (10 ** 2)
True
>>> (10 ** 3) is (10 ** 3)
False
>>> 1000 is 1000
True
I used the disassembler, but I completely missed that although `1000 is 1000` and `(10 3) is (10 3)` both get optimized to nearly identical bytecode they load different constants. I wrote it up in a new post and thanked you both. https://kate.io/blog/2017/08/24/python-constants-in-bytecode... >>> def f():
... x = 2221+1; y=2221+1
... return x is y
>>> f()
False
>>> f.__code__.co_consts
(None, 2221, 1, 2222, 2222)
>>> dis.dis(f)
2 0 LOAD_CONST 3 (2222)
2 STORE_FAST 0 (x)
4 LOAD_CONST 4 (2222)
6 STORE_FAST 1 (y)
3 8 LOAD_FAST 0 (x)
10 LOAD_FAST 1 (y)
12 COMPARE_OP 8 (is)
14 RETURN_VALUE
Not too sure when stuff like this would be useful (it goes way beyond the 'avoid using is unless checking references` advice), but it sure is fun.The tricky bit is that everything is an object in Python, even "primitives" like integers, which can be surprising coming from some other languages. Then the trickier bit is that CPython (the most popular and standard implementation) on startup creates an object for every int from -5 to 256 and will re-use those instead of creating a new PyLongObject. This means that `256 is 256` works, because under the hood, it's short-circuting it to the same object. But `257 is 257` creates 2 different PyLongObjects, which have the same value, 257, but aren't technically the same object.
And in my above example, the reason `x = 257; x is 257` is True when on the same line, but False when on separate lines (in the REPL) is because of the reasons kmill says, the constants pool that the interpreter creates. If they're interpreted together, it will create and use the same constant.
Here is my entry on my company's blog about this. I won't guarantee you it's well written, but it does show bytecode and has links to the relevant C source lines at the very end.
https://www.everymundo.com/literals-other-number-oddities-py...
MOST-NEGATIVE-FIXNUM, value: -1152921504606846976
MOST-POSITIVE-FIXNUM, value: 1152921504606846975
Fixnums are typically stored inline in data structures (like lists, arrays and CLOS objects). Bignums will be stored as a pointer to an heap-allocated large number. Data has tags and thus in a 64bit Lisp the fixnums will be slightly smaller than 64bit. Bignums can be 'arbitrary' larger and there is automatic switching between fixnums and bignums for numeric operations. In [7]: a = "foo"
In [8]: b = "foo"
In [9]: a is b
Out[9]: True
In [10]: b = "foobaljlajdfsklfjds l;kjsl;dfj ls;dfj l;skdj flsdjluejsklnm "
In [11]: a = "foobaljlajdfsklfjds l;kjsl;dfj ls;dfj l;skdj flsdjluejsklnm "
In [12]: a is b
Out[12]: False
Seems to work with small and big strings too.https://hg.python.org/cpython/file/f254ceec0d45/Objects/code...
Its not actually length, its whether the string looks like it could be a python name, and it only happens for string literals.
http://www.ianbicking.org/blog/2008/12/the-magic-sentinel.ht...
But I'd estimate 99% of the times I've used `is` was for comparisons to `None`, and 90% of the rest of times for comparisons to other sentinel values.
No, it is not good practice to rely on the interning of ints and short strings. It's implementation-specific behavior and relying on it can cause your code to not work on PyPy or even potentially a future version of CPython.
Idiomatically, you generally only see `is` used for comparison to `None`. Sometimes developers want to check identity, and you'd use `is` there too (but I don't have a handy example offhand).
http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#...
(here == means reference not value equality)
"If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == b."
If you're going to have a conditional that will evaluate to True most of the time, sometimes (in Python) it's considered better to just go ahead and try the logic that the conditional is guarding, and then catch the exception and handle it if it happens.
Unfortunately this blog post seems to miss a great opportunity to show you how you should compare integers for equality -- using the equality operator `==` and not the identity comparison `is`.
EDIT: odd, this post attracted a lot of downvotes. Please help me learn how this post could be improved.
Then you look at something like C#, where == compares values for value types and references for reference types, except that == is overloaded for some "value-like" reference types like String... it's a mess.
OTOH, Java is consistent in a sense that == never dereferences, but awkward in practice because of the need to use equals() for strings, which is too verbose for an operation that's far more common than object identity comparison.
And to avoid issues with is/==, we recommend our students to always use == (except for `is None`). Also related piece:https://blog.rmotr.com/avoiding-being-bitten-by-python-161b0...
[1]> (eq (expt 2 47) (expt 2 47))
T
[2]> (eq (expt 2 48) (expt 2 48))
NIL
Explanation here: https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node17.htmlre python: this is of course superlame. the compiler can easily detect "is <int>" and forbid the const int table optimization. Only "is None" would make sense.
>>> 42 == 0
True
https://lameiro.wordpress.com/2010/07/18/deixando-o-interpre...Equal Rights for Functional Objects or, The More Things Change, The More They Are the Same (1993) by Henry Baker
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.23.9...
b = 1000
a is b
The output is false only if you use the REPL. Run a .py script writing the above code and it returns True. I read about it on SO but can't find the link to it!
It's not necessarily a common thing. Most people aren't running python directly on the internet but being able to screw around with stuff like this is just another important tool in the toolbox when you're attacking something.
> has 4-byte arbitrary global write primitive
> uses it to change arithmetic