2012-02-28

unholy python

import dis, sys

def return_value_used():
    frame = sys._getframe(2)
    code = frame.f_code.co_code[frame.f_lasti:]
    try:
        has_arg = ord(code[0]) >= dis.HAVE_ARGUMENT
        next_code = code[3 if has_arg else 1]
    except IndexError:
        return True
    return ord(next_code) != dis.opmap['POP_TOP']

def foo():
    if return_value_used():
        return 42
    print 'doom'

foo()
print foo()
--
This outputs:
doom
42

Well that's... unholy.

(I'm also quite late to this party; Youtube video of the talk or the pdf)