Skip to content

Instantly share code, notes, and snippets.

@kjelly
Created December 16, 2013 14:24
Show Gist options
  • Save kjelly/7987698 to your computer and use it in GitHub Desktop.
Save kjelly/7987698 to your computer and use it in GitHub Desktop.
python 在處理 closure 時,編譯時期就會偵測是否有使用 closure ,有的話,則會特別產生一些給 closure 用的 opcode。下面例子,會產生一些給 closure 用的 opcode。如果你把 print value 改成其他名稱,則不會產生 closure 的 opcode。
def get_func():
value = 's'
def test():
print value
return test
import dis
dis.dis(get_func)
@kjelly
Copy link
Author

kjelly commented Dec 16, 2013

closure 相關的 opcode:

STORE_DEREF
LOAD_DEREF

LOAD_CLOSURE
MAKE_CLOSURE

@kjelly
Copy link
Author

kjelly commented Dec 16, 2013

get_func 的 value 叫做 co_cellvars
test的 value 叫做 co_freevars

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment