Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I guess you mean "N". 10 is a literal, not a name. The part "N cannot be assumed to be ten, because that could be changed elsewhere in the code" implies well enough that the change could be to a non-integer value. (For that matter, writing `N: int = 10` does nothing to fix that.)


No, I mean the literal. CPython is more flexible than it has any right to be, and you're free to edit the memory pointed to by the literal 10.


Care to show how you believe this can be achieved, from within Python?


  import ctypes

  ten = 10
  addr = id(ten)
  
  class PyLongObject(ctypes.Structure):
      _fields_ = [
          ("ob_refcnt", ctypes.c_ssize_t),
          ("ob_type", ctypes.c_void_p),
          ("ob_size", ctypes.c_ssize_t),
          ("ob_digit", ctypes.c_uint32 * 1),
      ]
  long_obj = PyLongObject.from_address(addr)
  
  long_obj.ob_digit[0] = 3
  assert 10 == 3
  
  # using an auxiliary variable to prevent any inlining
  # done at the interpreter level before actually querying
  # the value of the literal `10`
  x = 3
  assert 10 * x == 9
  assert 10 + x == 6


Okay, but this is going out of one's way to view the runtime itself as a C program and connect to it with the FFI. For that matter, the notion that the result of `id` (https://docs.python.org/3/library/functions.html#id) could sensibly be passed to `from_address` is an implementation detail. This is one reason the language suffers from not having a formal specification: it's unclear exactly how much of this madness alternative implementations like PyPy are expected to validate against. But I think people would agree that poking at the runtime's own memory cannot be expected to give deterministic results, and thus the implementation should in fact consider itself free to assume that isn't happening. (After all, we could take that further; e.g. what if we had another process do the dirty work?)


Except, that sort of thing is important in places like gevent, pytest, and numba, and that functionality isn't easy to replace without a lot of additional language/stdlib work (no sane developer would reach for it if other APIs sufficed).

The absurd example of overwriting the literal `10` is "obviously" bad, but your assertion that the interpreter should be able to assume nobody is overwriting its memory isn't borne out in practice.


> Except, that sort of thing is important in places like gevent, pytest, and numba

What, mutating the data representation of built-in types documented to be immutable? For what purpose?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: