Brendan Abel Brendan Abel - 2 months ago 5
Python Question

What does dis.findlabels() do?

I was playing around with the

dis
library to gather information about a function (like what other functions it called). The documentation for
dis.findlabels
sounds like it would return other function calls, but I've tried it with a handful of functions and it always returns an empty list.


dis.findlabels(code)

Detect all offsets in the code object code which
are jump targets, and return a list of these offsets.



What is this function supposed to do and how would you use it?

Answer

For example, this function has one jump:

def f(x):
    if x > 0:     # This will jump to "return 2" if not x > 0
        return 1
    else:
        return 2

See it here:

>>> dis.disco(f.__code__)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (0)
              6 COMPARE_OP               4 (>)
              9 POP_JUMP_IF_FALSE       16

  3          12 LOAD_CONST               2 (1)
             15 RETURN_VALUE

  5     >>   16 LOAD_CONST               3 (2)
             19 RETURN_VALUE
             20 LOAD_CONST               0 (None)
             23 RETURN_VALUE

There is one jump to 16 in 9 POP_JUMP_IF_FALSE 16

Therefore, findlabels finds that jump target:

>>> dis.findlabels(f.__code__.co_code)
[16]