In what scenario is it useful to use disassembly in python?

The dis module can be used effectively to demonstrate Python methods, functions, and classes in low-level translator instructions.

I know that disinformation can be used to:
1. Find the race status in programs using threads
2. Find possible optimizations

From your experience, do you know of any other scenarios in which the Python disassembly function might be useful?

+3
source share
3 answers

dis . , Python, - "" Python - "" ( ) . , Python , " " "" Python: , " " ( , , ;-) .

+5

dis , , , , , .

: list += [item] vs list.append(item)

def f(x): return 2*x

def f1(func, nums):
  result = []
  for item in nums:
    result += [fun(item)]
  return result

def f2(func, nums):                       
  result = []
  for item in nums:
    result.append(fun(item))
  return result

timeit.timeit , f2(f, range(100)) , f1(f, range(100). ?

(, f2 , map(f, range(100)).)

f1

dis, dis.dis(f1), 4.

  4          19 LOAD_FAST                2 (result)
             22 LOAD_FAST                1 (fun)
             25 LOAD_FAST                3 (item)
             28 CALL_FUNCTION            1 
             31 BUILD_LIST               1 
             34 INPLACE_ADD                
             35 STORE_FAST               2 (result) 
             38 JUMP_ABSOLUTE           13 
        >>   41 POP_BLOCK           

f2

, 4:

  4          19 LOAD_FAST                2 (result)
             22 LOAD_ATTR                0 (append)
             25 LOAD_FAST                1 (fun)
             28 LOAD_FAST                3 (item)
             31 CALL_FUNCTION            1 
             34 CALL_FUNCTION            1 
             37 POP_TOP                    
             38 JUMP_ABSOLUTE           13 
        >>   41 POP_BLOCK           

f1 :

  • fun on item ( 28)
  • ( 31, !)
  • result ( 34)
  • result ( 35)

f2 :

  • fun item ( 31)
  • append on result ( 34; C: !)

, (imho) list += [value] , list.append().


, dis.dis .pyc , , :)

+7

Python . , , - , . , , . , .

, - , , . , - , ? :

>>> def f():
...     def foo(x=[1, 2, 3]):
...         y = [4,]
...         return x + y
... 
>>> dis(f)
  2           0 LOAD_CONST               1 (1)
              3 LOAD_CONST               2 (2)
              6 LOAD_CONST               3 (3)
              9 BUILD_LIST               3
             12 LOAD_CONST               4 (<code object foo at 0xb7690770, file "<stdin>", line 2>)
             15 MAKE_FUNCTION            1
             18 STORE_FAST               0 (foo)
             21 LOAD_CONST               0 (None)
             24 RETURN_VALUE        

You can see this happening by pushing constants 1, 2 and 3 onto the stack, putting what is on the stack into the list, loading it into the code object, making the code function into the object and saving it to the foo variable.

+3
source

Source: https://habr.com/ru/post/1741955/


All Articles