Last active
December 31, 2015 23:58
-
-
Save garcia/8063145 to your computer and use it in GitHub Desktop.
Self-referencing tuple in 32-bit CPython 2.7.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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