2016-03-29 42 views
3

我正在使用緩存系統。這個想法是,它可以檢測創建緩存對象的函數自初始創建以來是否發生了變化,因此使緩存文件無效。什麼是函數.__ code__跨多個程序執行的行爲?

我偶然發現了python的function.__code__屬性,這是編譯函數的字節碼錶示。我無法找到關於此事的其他文檔,並且想知道在單個程序的不同執行過程中它的行爲是什麼。

我認爲,因爲python是一種解釋型語言,字節碼將獨立於平臺。我還假設它的字節碼生成對於給定的輸入是確定性的。我是這麼想的嗎?

+1

我認爲它可能會隨着解釋器版本而改變 – wRAR

回答

2

函數.__ code__屬性返回封裝虛擬機字節碼的對象。

def f(): return 3 
print(dir(f.__code__)) 
print(f.__code__.co_code) # raw compiled bytecode 

訪問信息的另一種方法是顯式編譯一個文件。 這裏是一個文件test.py

def f(): return 3 

然後,您可以鍵入蟒蛇提示:

>>> c = compile('test.py', 'test.py', 'exec') 
>>> print(c.co_code) # here is some bytecode 

一個簡單而有趣的方式來訪問字節碼,在一個非常清晰的方式,是運行它在終端(這裏,是dis拆裝):

python -m dis test.py 

,其輸出:

1   0 LOAD_CONST    0 (<code object f at 0x7fe8a5902300, file "p.py", line 1>) 
      3 LOAD_CONST    1 ('f') 
      6 MAKE_FUNCTION   0 
      9 STORE_NAME    0 (f) 
     12 LOAD_CONST    2 (None) 
     15 RETURN_VALUE 

該字節碼不依賴於平臺。虛擬機是。


關於在字節碼可能的變化,我已經採取this file,並拆卸了兩遍:

python3 -m dis file.py > test1 
python3 -m dis file.py > test2 

然後一個簡單的差異表明:

89c89 
< 26   204 LOAD_CONST    13 (<code object search_concept at 0x7f40de337300, file "powergrasp/compression.py", line 26>) 
--- 
> 26   204 LOAD_CONST    13 (<code object search_concept at 0x7fd8de5ab300, file "powergrasp/compression.py", line 26>) 
104c104 
<    240 LOAD_CONST    19 (<code object compress_lp_graph at 0x7f40de340780, file "powergrasp/compression.py", line 55>) 
--- 
>    240 LOAD_CONST    19 (<code object compress_lp_graph at 0x7fd8de5b4780, file "powergrasp/compression.py", line 55>) 

的變化主要是關於進口,其中加載模塊的地址在編譯過程中不相同。

相關問題