Note: Byte code we are dealing with here is a CPython implementation detail. Don't expect it to work on other implementations of Python. Prefer Jon Clements's approach.
In CPython 3.4+ you can use dis.get_instructions
to check if BINARY_POWER
instruction is present in function's code object or not(Also explained in What's new in Python 3.4 doc):
>>> import dis
>>> def search_instruction(code_object, instr_code):
for ins in dis.get_instructions(code_object):
if ins.opcode == instr_code:
return True
return False
...
>>> def f1():
s = x ** 2
...
>>> def f2():
s = 'x ** 2'
...
>>> dis.opmap['BINARY_POWER']
19
>>> search_instruction(f1.__code__, 19)
True
>>> search_instruction(f2.__code__, 19)
False
For CPython 2.X specifically you can try byteplay
package available on PyPI(its Python 3 fork: https://github.com/serprex/byteplay).:
>>> import byteplay
>>> def search_instruction(code_object, instr_code):
for ins, _ in byteplay.Code.from_code(code_object).code:
if ins == instr_code:
return True
return False
...
>>> search_instruction(f1.__code__, 19)
True
>>> search_instruction(f2.__code__, 19)
False
Related: Bytecode: What, Why, and How to Hack it - Dr. Ryan F Kelly