Skip to content

Instantly share code, notes, and snippets.

@garcia
Last active December 31, 2015 23:58
Show Gist options
  • Save garcia/8063145 to your computer and use it in GitHub Desktop.
Save garcia/8063145 to your computer and use it in GitHub Desktop.
Self-referencing tuple in 32-bit CPython 2.7.
import ctypes
import struct
import sys
# Goal: obtain something like "outer = (outer,)", even though that's impossible with vanilla Python
inner = ()
outer = (inner,)
# Get CPython's internal representation of the outer tuple
c_outer = (ctypes.c_char * sys.getsizeof(outer)).from_address(id(outer))
# Find where it keeps the pointer to the inner tuple
inner_index = c_outer[:].find(struct.pack('P', id(inner)))
# Replace the inner tuple's address with that of the outer tuple
c_outer[inner_index:inner_index+struct.calcsize('P')] = struct.pack('P', id(outer))
# Tuples don't handle self-references very well...
print outer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment