On Tue, May 28, 2013 at 1:58 PM, Oscar Benjamin <oscar.j.benja...@gmail.com> wrote: > > So what happens to the code object for the top-level code in the > module itself when it is imported in the normal way? Is it just > discarded once import is complete? Is it temporarily accessible during > import?
Normally, nothing holds a reference to it, so it gets deallocated, as do the anonymous functions used to build classes. However, in CPython the current frame is accessible during import via sys._getframe(). The code object is the f_code attribute: >>> code = compile(r''' ... import sys ... frame = sys._getframe() ... ''', '<test>', 'exec') >>> >>> ns = {} >>> exec code in ns >>> dis.dis(ns['frame'].f_code) 2 0 LOAD_CONST 0 (0) 3 LOAD_CONST 1 (None) 6 IMPORT_NAME 0 (sys) 9 STORE_NAME 0 (sys) 3 12 LOAD_NAME 0 (sys) 15 LOAD_ATTR 1 (_getframe) 18 CALL_FUNCTION 0 21 STORE_NAME 2 (frame) 24 LOAD_CONST 1 (None) 27 RETURN_VALUE _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor