py33compat.py 1020 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import dis
  2. import array
  3. import collections
  4. import six
  5. OpArg = collections.namedtuple('OpArg', 'opcode arg')
  6. class Bytecode_compat(object):
  7. def __init__(self, code):
  8. self.code = code
  9. def __iter__(self):
  10. """Yield '(op,arg)' pair for each operation in code object 'code'"""
  11. bytes = array.array('b', self.code.co_code)
  12. eof = len(self.code.co_code)
  13. ptr = 0
  14. extended_arg = 0
  15. while ptr < eof:
  16. op = bytes[ptr]
  17. if op >= dis.HAVE_ARGUMENT:
  18. arg = bytes[ptr + 1] + bytes[ptr + 2] * 256 + extended_arg
  19. ptr += 3
  20. if op == dis.EXTENDED_ARG:
  21. long_type = six.integer_types[-1]
  22. extended_arg = arg * long_type(65536)
  23. continue
  24. else:
  25. arg = None
  26. ptr += 1
  27. yield OpArg(op, arg)
  28. Bytecode = getattr(dis, 'Bytecode', Bytecode_compat)