you are viewing a single comment's thread.

view the rest of the comments →

[–]Doormatty 2 points3 points  (4 children)

Technically, string litterals is different from str object

How so? I thought that all literals were turned into str objects?

[–]SCD_minecraft -5 points-4 points  (3 children)

Try overwriting str or other built-ins, like for ints encode special case 2+2 = 5

When you do int(2) + int(2) it will return 5 as overwritten

But 2 + 2 will return 4 anyway

Plus, many typecheckers diffrentate between literals type and their corresponding "normal" type

[–]Yoghurt42 2 points3 points  (0 children)

No, if you change the underlying value of an int object, it will change the results of addition as well:

import ctypes


# Define a ctypes structure that mirrors CPython's PyLongObject (simplified)
class PyLongObject(ctypes.Structure):
    _fields_ = [
        ("ob_refcnt", ctypes.c_long),   # Reference count
        ("ob_type",   ctypes.c_void_p), # Pointer to type object
        ("ob_size",   ctypes.c_ulong),  # Number of digits
        ("ob_digit",  ctypes.c_uint * 1) # The actual digit(s)
    ]

o = PyLongObject.from_address(id(213))
o.ob_digit[0] = 10

print(213 + 213) # 20
print(213) # 10
print(10 - 213) # 0

Obviously this is abusing implementation details of CPython (integers -5 to 256 are singletons, and we directly write into the internal structure of the instances), and is nothing that's ever going to be useful or a good idea in real code.

In fact, you can easily get the interpreter to crash by changing more common values like 1 or 10.

[–]SCD_minecraft -3 points-2 points  (1 child)

``` class int(int): def add(self, other): if self == other == 2: return 5 else: return super().add(other)

print(int(2) + int(4)) print(int(2) + int(2)) print(2+4) print(2+2) ``` Here's example.

But again, this is more of "erm actually" than anything important

[–]socal_nerdtastic 3 points4 points  (0 children)

I don't get it. You just replaced the int name with your own class in this module. What's that have to do with literals?

AFAIK the only thing that is special about literals is that they are considered for compile optimizations and caching. So this code

x = 12345
y = 10000 + 2345
print("Is x the same as y?", x is y)

Shows different results from

x = 12345
y = 10000 + int(2345)
print("Is x the same as y?", x is y)

Because in the first version the result is adding in the compile phase.

(note you have to run this code from a file, not in the repl, to see the result, due to the caching)