python
Python 3.5
sys.modules is a dictionary mapping the names of imported modules to the module object holding the code
True
['IPython',
'IPython.core',
'IPython.core.alias',
'IPython.core.application',
'IPython.core.autocall',
'IPython.core.builtin_trap',
'IPython.core.compilerop',
'IPython.core.completer',
'IPython.core.completerlib',
'IPython.core.crashhandler',
'IPython.core.debugger',
'IPython.core.display',
'IPython.core.display_trap',
'IPython.core.displayhook',
'IPython.core.displaypub',
'IPython.core.error',
'IPython.core.events',
'IPython.core.excolors',
'IPython.core.extensions',
'IPython.core.formatters',
'IPython.core.getipython',
'IPython.core.history',
'IPython.core.hooks',
'IPython.core.inputsplitter',
'IPython.core.inputtransformer',
'IPython.core.interactiveshell',
'IPython.core.latex_symbols',
'IPython.core.logger',
'IPython.core.macro',
'IPython.core.magic',
'IPython.core.magic_arguments',
'IPython.core.magics',
'IPython.core.magics.auto',
'IPython.core.magics.basic',
'IPython.core.magics.code',
'IPython.core.magics.config',
'IPython.core.magics.display',
'IPython.core.magics.execution',
'IPython.core.magics.extension',
'IPython.core.magics.history',
'IPython.core.magics.logging',
'IPython.core.magics.namespace',
'IPython.core.magics.osm',
'IPython.core.magics.pylab',
'IPython.core.magics.script',
'IPython.core.oinspect',
'IPython.core.page',
'IPython.core.payload',
'IPython.core.payloadpage',
'IPython.core.prefilter',
'IPython.core.profiledir',
'IPython.core.pylabtools',
'IPython.core.release',
'IPython.core.shellapp',
'IPython.core.splitinput',
'IPython.core.ultratb',
'IPython.core.usage',
'IPython.display',
'IPython.extensions',
'IPython.extensions.storemagic',
'IPython.lib',
'IPython.lib.backgroundjobs',
'IPython.lib.clipboard',
'IPython.lib.display',
'IPython.lib.pretty',
'IPython.lib.security',
'IPython.paths',
'IPython.terminal',
'IPython.terminal.debugger',
'IPython.terminal.embed',
'IPython.terminal.interactiveshell',
'IPython.terminal.ipapp',
'IPython.terminal.magics',
'IPython.terminal.prompts',
'IPython.terminal.pt_inputhooks',
'IPython.terminal.ptutils',
'IPython.terminal.shortcuts',
'IPython.testing',
'IPython.testing.skipdoctest',
'IPython.utils',
'IPython.utils.PyColorize',
'IPython.utils._process_common',
'IPython.utils._process_posix',
'IPython.utils._sysinfo',
'IPython.utils.capture',
'IPython.utils.colorable',
'IPython.utils.coloransi',
'IPython.utils.contexts',
'IPython.utils.data',
'IPython.utils.decorators',
'IPython.utils.dir2',
'IPython.utils.encoding',
'IPython.utils.frame',
'IPython.utils.generics',
'IPython.utils.importstring',
'IPython.utils.io',
'IPython.utils.ipstruct',
'IPython.utils.module_paths',
'IPython.utils.openpy',
'IPython.utils.path',
'IPython.utils.process',
'IPython.utils.py3compat',
'IPython.utils.sentinel',
'IPython.utils.strdispatch',
'IPython.utils.sysinfo',
'IPython.utils.syspathcontext',
'IPython.utils.tempdir',
'IPython.utils.terminal',
'IPython.utils.text',
'IPython.utils.timing',
'IPython.utils.tokenize2',
'IPython.utils.tokenutil',
'IPython.utils.wildcard',
'__future__',
'__main__',
'__mp_main__',
'_ast',
'_bisect',
'_bootlocale',
'_bz2',
'_codecs',
'_collections',
'_collections_abc',
'_compat_pickle',
'_compression',
'_ctypes',
'_curses',
'_cython_0_25_1',
'_datetime',
'_decimal',
'_frozen_importlib',
'_frozen_importlib_external',
'_functools',
'_hashlib',
'_heapq',
'_imp',
'_io',
'_json',
'_locale',
'_lsprof',
'_lzma',
'_multiprocessing',
'_opcode',
'_operator',
'_pickle',
'_posixsubprocess',
'_random',
'_signal',
'_sitebuiltins',
'_socket',
'_sqlite3',
'_sre',
'_stat',
'_string',
'_strptime',
'_struct',
'_sysconfigdata',
'_sysconfigdata_m',
'_thread',
'_warnings',
'_weakref',
'_weakrefset',
'abc',
'apport_python_hook',
'argparse',
'array',
'ast',
'atexit',
'base64',
'bdb',
'binascii',
'bisect',
'builtins',
'bz2',
'cProfile',
'calendar',
'cmd',
'code',
'codecs',
'codeop',
'collections',
'collections.abc',
'concurrent',
'concurrent.futures',
'concurrent.futures._base',
'concurrent.futures.process',
'concurrent.futures.thread',
'contextlib',
'copy',
'copyreg',
'ctypes',
'ctypes._endian',
'ctypes.util',
'curses',
'datetime',
'dateutil',
'dateutil._common',
'dateutil.parser',
'dateutil.relativedelta',
'dateutil.tz',
'dateutil.tz._common',
'dateutil.tz.tz',
'decimal',
'decorator',
'difflib',
'dis',
'email',
'email._encoded_words',
'email._parseaddr',
'email._policybase',
'email.base64mime',
'email.charset',
'email.encoders',
'email.errors',
'email.feedparser',
'email.header',
'email.iterators',
'email.message',
'email.parser',
'email.quoprimime',
'email.utils',
'encodings',
'encodings.aliases',
'encodings.latin_1',
'encodings.utf_8',
'enum',
'errno',
'faulthandler',
'fcntl',
'fnmatch',
'functools',
'gc',
'genericpath',
'getopt',
'getpass',
'gettext',
'glob',
'grp',
'hashlib',
'heapq',
'hmac',
'html',
'html.entities',
'imp',
'importlib',
'importlib._bootstrap',
'importlib._bootstrap_external',
'importlib.abc',
'importlib.machinery',
'importlib.util',
'inspect',
'io',
'ipykernel',
'ipykernel._version',
'ipykernel.codeutil',
'ipykernel.comm',
'ipykernel.comm.comm',
'ipykernel.comm.manager',
'ipykernel.connect',
'ipykernel.datapub',
'ipykernel.displayhook',
'ipykernel.heartbeat',
'ipykernel.iostream',
'ipykernel.ipkernel',
'ipykernel.jsonutil',
'ipykernel.kernelapp',
'ipykernel.kernelbase',
'ipykernel.parentpoller',
'ipykernel.pickleutil',
'ipykernel.serialize',
'ipykernel.zmqshell',
'ipython_genutils',
'ipython_genutils._version',
'ipython_genutils.encoding',
'ipython_genutils.importstring',
'ipython_genutils.path',
'ipython_genutils.py3compat',
'ipython_genutils.text',
'ipywidgets',
'ipywidgets._version',
'ipywidgets.widgets',
'ipywidgets.widgets.domwidget',
'ipywidgets.widgets.interaction',
'ipywidgets.widgets.trait_types',
'ipywidgets.widgets.valuewidget',
'ipywidgets.widgets.widget',
'ipywidgets.widgets.widget_bool',
'ipywidgets.widgets.widget_box',
'ipywidgets.widgets.widget_button',
'ipywidgets.widgets.widget_color',
'ipywidgets.widgets.widget_controller',
'ipywidgets.widgets.widget_core',
'ipywidgets.widgets.widget_date',
'ipywidgets.widgets.widget_float',
'ipywidgets.widgets.widget_image',
'ipywidgets.widgets.widget_int',
'ipywidgets.widgets.widget_layout',
'ipywidgets.widgets.widget_link',
'ipywidgets.widgets.widget_output',
'ipywidgets.widgets.widget_selection',
'ipywidgets.widgets.widget_selectioncontainer',
'ipywidgets.widgets.widget_string',
'ipywidgets.widgets.widget_style',
'itertools',
'jedi',
'jedi._compatibility',
'jedi.api',
'jedi.api.classes',
'jedi.api.completion',
'jedi.api.helpers',
'jedi.api.interpreter',
'jedi.api.keywords',
'jedi.api.usages',
'jedi.cache',
'jedi.common',
'jedi.debug',
'jedi.evaluate',
'jedi.evaluate.analysis',
'jedi.evaluate.cache',
'jedi.evaluate.compiled',
'jedi.evaluate.compiled.fake',
'jedi.evaluate.compiled.mixed',
'jedi.evaluate.context',
'jedi.evaluate.docstrings',
'jedi.evaluate.dynamic',
'jedi.evaluate.filters',
'jedi.evaluate.finder',
'jedi.evaluate.flow_analysis',
'jedi.evaluate.helpers',
'jedi.evaluate.imports',
'jedi.evaluate.instance',
'jedi.evaluate.iterable',
'jedi.evaluate.param',
'jedi.evaluate.pep0484',
'jedi.evaluate.precedence',
'jedi.evaluate.recursion',
'jedi.evaluate.representation',
'jedi.evaluate.site',
'jedi.evaluate.stdlib',
'jedi.evaluate.sys_path',
'jedi.parser',
'jedi.parser.cache',
'jedi.parser.parser',
'jedi.parser.pgen2',
'jedi.parser.pgen2.grammar',
'jedi.parser.pgen2.parse',
'jedi.parser.pgen2.pgen',
'jedi.parser.python',
'jedi.parser.python.diff',
'jedi.parser.python.parser',
'jedi.parser.python.tree',
'jedi.parser.token',
'jedi.parser.tokenize',
'jedi.parser.tree',
'jedi.settings',
'json',
'json.decoder',
'json.encoder',
'json.scanner',
'jupyter_client',
'jupyter_client._version',
'jupyter_client.adapter',
'jupyter_client.blocking',
'jupyter_client.blocking.channels',
'jupyter_client.blocking.client',
'jupyter_client.channels',
'jupyter_client.channelsabc',
'jupyter_client.client',
'jupyter_client.clientabc',
'jupyter_client.connect',
'jupyter_client.jsonutil',
'jupyter_client.kernelspec',
'jupyter_client.launcher',
'jupyter_client.localinterfaces',
'jupyter_client.manager',
'jupyter_client.managerabc',
'jupyter_client.multikernelmanager',
'jupyter_client.session',
'jupyter_core',
'jupyter_core.paths',
'jupyter_core.version',
'keyrings',
'keyword',
'linecache',
'locale',
'logging',
'logging.handlers',
'lzma',
'marshal',
'math',
'mimetypes',
'multiprocessing',
'multiprocessing.connection',
'multiprocessing.context',
'multiprocessing.process',
'multiprocessing.reduction',
'multiprocessing.util',
'ntpath',
'numbers',
'opcode',
'operator',
'optparse',
'os',
'os.path',
'pathlib',
'pdb',
'pexpect',
'pexpect.exceptions',
'pexpect.expect',
'pexpect.pty_spawn',
'pexpect.run',
'pexpect.spawnbase',
'pexpect.utils',
'pickle',
'pickleshare',
'pkg_resources',
'pkg_resources._vendor',
'pkg_resources._vendor.packaging.__about__',
'pkg_resources._vendor.six',
'pkg_resources._vendor.six.moves',
'pkg_resources.extern',
'pkg_resources.extern.appdirs',
'pkg_resources.extern.packaging',
'pkg_resources.extern.packaging._compat',
'pkg_resources.extern.packaging._structures',
'pkg_resources.extern.packaging.markers',
'pkg_resources.extern.packaging.requirements',
'pkg_resources.extern.packaging.specifiers',
'pkg_resources.extern.packaging.version',
'pkg_resources.extern.pyparsing',
'pkg_resources.extern.six',
'pkg_resources.extern.six.moves',
'pkg_resources.extern.six.moves.urllib',
'pkgutil',
'platform',
'plistlib',
'posix',
'posixpath',
'pprint',
'profile',
'prompt_toolkit',
'prompt_toolkit.application',
'prompt_toolkit.auto_suggest',
'prompt_toolkit.buffer',
'prompt_toolkit.buffer_mapping',
'prompt_toolkit.cache',
'prompt_toolkit.clipboard',
'prompt_toolkit.clipboard.base',
'prompt_toolkit.clipboard.in_memory',
'prompt_toolkit.completion',
'prompt_toolkit.document',
'prompt_toolkit.enums',
'prompt_toolkit.eventloop',
'prompt_toolkit.eventloop.base',
'prompt_toolkit.eventloop.callbacks',
'prompt_toolkit.filters',
'prompt_toolkit.filters.base',
'prompt_toolkit.filters.cli',
'prompt_toolkit.filters.types',
'prompt_toolkit.filters.utils',
'prompt_toolkit.history',
'prompt_toolkit.input',
'prompt_toolkit.interface',
'prompt_toolkit.key_binding',
'prompt_toolkit.key_binding.bindings',
'prompt_toolkit.key_binding.bindings.basic',
'prompt_toolkit.key_binding.bindings.completion',
'prompt_toolkit.key_binding.bindings.emacs',
'prompt_toolkit.key_binding.bindings.named_commands',
'prompt_toolkit.key_binding.bindings.scroll',
'prompt_toolkit.key_binding.bindings.vi',
'prompt_toolkit.key_binding.defaults',
'prompt_toolkit.key_binding.digraphs',
'prompt_toolkit.key_binding.input_processor',
'prompt_toolkit.key_binding.manager',
'prompt_toolkit.key_binding.registry',
'prompt_toolkit.key_binding.vi_state',
'prompt_toolkit.keys',
'prompt_toolkit.layout',
'prompt_toolkit.layout.containers',
'prompt_toolkit.layout.controls',
'prompt_toolkit.layout.dimension',
'prompt_toolkit.layout.lexers',
'prompt_toolkit.layout.margins',
'prompt_toolkit.layout.menus',
'prompt_toolkit.layout.mouse_handlers',
'prompt_toolkit.layout.processors',
'prompt_toolkit.layout.prompt',
'prompt_toolkit.layout.screen',
'prompt_toolkit.layout.toolbars',
'prompt_toolkit.layout.utils',
'prompt_toolkit.mouse_events',
'prompt_toolkit.output',
'prompt_toolkit.reactive',
'prompt_toolkit.renderer',
'prompt_toolkit.search_state',
'prompt_toolkit.selection',
'prompt_toolkit.shortcuts',
'prompt_toolkit.styles',
'prompt_toolkit.styles.base',
'prompt_toolkit.styles.defaults',
'prompt_toolkit.styles.from_dict',
'prompt_toolkit.styles.from_pygments',
'prompt_toolkit.styles.utils',
'prompt_toolkit.terminal',
'prompt_toolkit.terminal.vt100_input',
'prompt_toolkit.terminal.vt100_output',
'prompt_toolkit.token',
'prompt_toolkit.utils',
'prompt_toolkit.validation',
'pstats',
'pty',
'ptyprocess',
'ptyprocess.ptyprocess',
'ptyprocess.util',
'pwd',
'pydoc',
'pydoc_data',
'pydoc_data.topics',
'pyexpat',
'pyexpat.errors',
'pyexpat.model',
'pygments',
'pygments.filter',
'pygments.filters',
'pygments.formatter',
'pygments.formatters',
'pygments.formatters._mapping',
'pygments.formatters.html',
'pygments.lexer',
'pygments.lexers',
'pygments.lexers._mapping',
'pygments.lexers.python',
'pygments.modeline',
'pygments.plugin',
'pygments.regexopt',
'pygments.style',
'pygments.styles',
'pygments.styles.default',
'pygments.token',
'pygments.unistring',
'pygments.util',
'queue',
'quopri',
'random',
're',
'reprlib',
'resource',
'runpy',
'select',
'selectors',
'shlex',
'shutil',
'signal',
'simplegeneric',
'simplejson',
'simplejson._speedups',
'simplejson.compat',
'simplejson.decoder',
'simplejson.encoder',
'simplejson.scanner',
'site',
'sitecustomize',
'six',
'six.moves',
'socket',
'sqlite3',
'sqlite3.dbapi2',
'sre_compile',
'sre_constants',
'sre_parse',
'stat',
'storemagic',
'string',
'struct',
'subprocess',
'sys',
'sysconfig',
'tempfile',
'termios',
'textwrap',
'threading',
'time',
'timeit',
'token',
'tokenize',
'tornado',
'tornado.concurrent',
'tornado.escape',
'tornado.ioloop',
'tornado.log',
'tornado.platform',
'tornado.platform.auto',
'tornado.platform.common',
'tornado.platform.interface',
'tornado.platform.posix',
'tornado.speedups',
'tornado.stack_context',
'tornado.util',
'traceback',
'traitlets',
'traitlets._version',
'traitlets.config',
'traitlets.config.application',
'traitlets.config.configurable',
'traitlets.config.loader',
'traitlets.log',
'traitlets.traitlets',
'traitlets.utils',
'traitlets.utils.bunch',
'traitlets.utils.getargspec',
'traitlets.utils.importstring',
'traitlets.utils.sentinel',
'tty',
'types',
'typing',
'typing.io',
'typing.re',
'unicodedata',
'urllib',
'urllib.parse',
'uu',
'uuid',
'warnings',
'wcwidth',
'wcwidth.table_wide',
'wcwidth.table_zero',
'wcwidth.wcwidth',
'weakref',
'xml',
'xml.parsers',
'xml.parsers.expat',
'xml.parsers.expat.errors',
'xml.parsers.expat.model',
'zipfile',
'zipimport',
'zlib',
'zmq',
'zmq.backend',
'zmq.backend.cython',
'zmq.backend.cython._device',
'zmq.backend.cython._poll',
'zmq.backend.cython._version',
'zmq.backend.cython.constants',
'zmq.backend.cython.context',
'zmq.backend.cython.error',
'zmq.backend.cython.message',
'zmq.backend.cython.socket',
'zmq.backend.cython.utils',
'zmq.backend.select',
'zmq.error',
'zmq.eventloop',
'zmq.eventloop.ioloop',
'zmq.eventloop.zmqstream',
'zmq.sugar',
'zmq.sugar.attrsettr',
'zmq.sugar.constants',
'zmq.sugar.context',
'zmq.sugar.frame',
'zmq.sugar.poll',
'zmq.sugar.socket',
'zmq.sugar.stopwatch',
'zmq.sugar.tracker',
'zmq.sugar.version',
'zmq.utils',
'zmq.utils.constant_names',
'zmq.utils.jsonapi',
'zmq.utils.strtypes']
_ast
_bisect
_codecs
_collections
_datetime
_elementtree
_functools
_heapq
_imp
_io
_locale
_md5
_operator
_pickle
_posixsubprocess
_random
_sha1
_sha256
_sha512
_signal
_socket
_sre
_stat
_string
_struct
_symtable
_thread
_tracemalloc
_warnings
_weakref
array
atexit
binascii
builtins
errno
faulthandler
fcntl
gc
grp
itertools
marshal
math
posix
pwd
pyexpat
select
spwd
sys
syslog
time
unicodedata
xxsubtype
zipimport
zlib
/usr/lib/python35.zip
/usr/lib/python3.5
/usr/lib/python3.5/plat-x86_64-linux-gnu
/usr/lib/python3.5/lib-dynload
/home/splasky/.local/lib/python3.5/site-packages
/usr/local/lib/python3.5/dist-packages
/usr/lib/python3/dist-packages
/usr/local/lib/python3.5/dist-packages/IPython/extensions
/home/splasky/.ipython
Writing example.py
/home/splasky/jupyter-notebook/example.py
a
Changing the path between the initial import and the call to
reload()
means a different module may be loaded the second time.
Checking NoisyImportFinder support for NoisyImportFinder_PATH_TRIGGER
NoisyImportFinder looking for "target_module"
Import failed: No module named 'target_module'
['In', 'NamespaceMagics', 'NoisyImportFinder', 'Out', '_', '_10', '_7', '_Jupyter', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_getsizeof', '_i', '_i1', '_i10', '_i11', '_i12', '_i13', '_i14', '_i15', '_i16', '_i17', '_i18', '_i19', '_i2', '_i20', '_i21', '_i22', '_i23', '_i24', '_i3', '_i4', '_i5', '_i6', '_i7', '_i8', '_i9', '_ih', '_ii', '_iii', '_nms', '_oh', 'd', 'dis', 'example', 'exit', 'get_ipython', 'getsizeof', 'json', 'name', 'oo', 'pprint', 'print_function', 'quit', 'sys', 'var_dic_list']
1 0 LOAD_CONST 0 (0)
3 LOAD_CONST 1 (None)
6 IMPORT_NAME 0 (sys)
9 STORE_NAME 0 (sys)
12 LOAD_CONST 1 (None)
15 RETURN_VALUE
1 0 LOAD_CONST 0 (0)
3 LOAD_CONST 1 (None)
6 IMPORT_NAME 0 (os)
9 STORE_NAME 0 (os)
12 LOAD_CONST 1 (None)
15 RETURN_VALUE
<module 'sys' (built-in)>
<module 'os' from '/usr/lib/python3.5/os.py'>
Overwriting c_modules.c
Overwriting setup.py
python3 ./setup.py install
dis assembly the module
as same as like import python module
IMPORT_NAME:
Python source code is compiled into bytecode, the internal representation of a Python program in the CPython interpreter. The bytecode is also cached in .pyc files so that executing the same file is faster the second time (recompilation from source to bytecode can be avoided). This “intermediate language” is said to run on a virtual machine that executes the machine code corresponding to each bytecode. Do note that bytecodes are not expected to work between different Python virtual machines, nor to be stable between Python releases.
A list of bytecode instructions can be found in the documentation for the dis module.
Help on built-in function exec in module builtins:
exec(source, globals=None, locals=None, /)
Execute the given source in the context of globals and locals.
The source may be a string representing one or more Python statements
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
Help on built-in function eval in module builtins:
eval(source, globals=None, locals=None, /)
Evaluate the given source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
所以eval
執行的內容必須是expression
,而exec
是都可以執行,但是回傳值固定為None。
5
5
6
6
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-107-40888bad4179> in <module>()
1 eval('5') # x <- 5
----> 2 eval('%d + 6' % x) # x <- 11
3 eval('abs(%d)' % -100) # x <- 100
4 eval('x = 5') # INVALID; assignment is not an expression.
5 eval('if 1: x = 4') # INVALID; if is a statement, not an expression.
TypeError: %d format: a number is required, not generator
hello world
42
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2862, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-112-e920440df200>", line 1, in <module>
code_obj_signle=compile(code_str,'string','single')
File "string", line 4
hello()
^
SyntaxError: invalid syntax
而single 只接受oneline statment
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2862, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-113-686a1487d9cc>", line 1, in <module>
code_obj_eval=compile(code_str,'string','eval')
File "string", line 2
def hello():
^
SyntaxError: invalid syntax
hello
hello
8
Actually the statement "eval accepts only a single expression" applies only when a string (which contains Python source code) is passed to eval. Then it is internally compiled to bytecode using compile(source, '<string>', 'eval') This is where the difference really comes from.
If a code object (which contains Python bytecode) is passed to exec or eval, they behave identically, excepting for the fact that exec ignores the return value, still returning None always. So it is possible use eval to execute something that has statements, if you just compiled it into bytecode before instead of passing it as a string:
Hello
It should work.
exec
function (which was a statement in Python 2) is used for executing a dynamically created statement or program.eval
function does the same for a single expression, and returns the value of the expression.exec and eval both accept the program/expression to be run either as a str, unicode or bytes object containing source code, or as a code object which contains Python bytecode.
If a str/unicode/bytes containing source code was passed to exec, it behaves equivalently to:
and eval similarly behaves equivalent to:
Called with 42
Called with 42
84
Code objects represent byte-compiled executable Python code, or bytecode.
The difference between a code object and a function object is that the function object contains an explicit reference to the function’s globals (the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time). Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects.
可以參考python的inspect lib
inside include/code.h
['__class__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__le__',
'__lt__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'co_argcount',
'co_cellvars',
'co_code',
'co_consts',
'co_filename',
'co_firstlineno',
'co_flags',
'co_freevars',
'co_kwonlyargcount',
'co_lnotab',
'co_name',
'co_names',
'co_nlocals',
'co_stacksize',
'co_varnames']
b'd\x00\x00d\x01\x00\x84\x00\x00Z\x00\x00e\x00\x00\x83\x00\x00\x01d\x02\x00S'
[100,
0,
0,
100,
1,
0,
132,
0,
0,
90,
0,
0,
101,
0,
0,
131,
0,
0,
1,
100,
2,
0,
83]
Name: <module>
Filename: string
Argument count: 0
Kw-only arguments: 0
Number of locals: 0
Stack size: 2
Flags: NOFREE
Constants:
0: <code object hello at 0x7f01fc67f030, file "string", line 2>
1: 'hello'
2: None
Names:
0: hello
2 0 LOAD_CONST 0 (<code object hello at 0x7f01fc67f030, file "string", line 2>)
3 LOAD_CONST 1 ('hello')
6 MAKE_FUNCTION 0
9 STORE_NAME 0 (hello)
4 12 LOAD_NAME 0 (hello)
15 CALL_FUNCTION 0 (0 positional, 0 keyword pair)
18 POP_TOP
19 LOAD_CONST 2 (None)
22 RETURN_VALUE
和上面的code object做對照
100
100
132
90
101
131
1
100
83
100
'LOAD_CONST'
可以發現opcode是python的一個module,他負責定義python interpreter會用到的instruction,所以我們才可以透過dis來disassembly python bytecode,而code object是bytecode的表現形式。
python中opcode的value和python virtual machine所定義的instruction相同(定義於opcode.h中,和dis.opmap的value互相對應),因此可以透過實做interpreter(不管任何形式)產生的python bytecode來讓python virtual machine執行。
(<code object hello at 0x7f3768227d20, file "string", line 2>, 'hello', None)
b'\x0c\x03'
()
3
2 0 LOAD_CONST 0 (<code object print_hello at 0x7f01fc6fde40, file "string", line 2>)
3 LOAD_CONST 1 ('print_hello')
6 MAKE_FUNCTION 0
9 STORE_NAME 0 (print_hello)
5 12 LOAD_NAME 1 (hello)
15 LOAD_CONST 2 (10)
18 LOAD_CONST 3 (11)
21 CALL_FUNCTION 2 (2 positional, 0 keyword pair)
24 POP_TOP
25 LOAD_CONST 4 (None)
28 RETURN_VALUE
line number | bytecode offect | bytecode | bytecode argument |
---|---|---|---|
5 | 12 | LOAD_NAME | 0(hello) |
Bytecode(<function hello at 0x7f01fc74fd90>)
Help on Bytecode in module dis object:
class Bytecode(builtins.object)
| The bytecode operations of a piece of code
|
| Instantiate this with a function, method, string of code, or a code object
| (as returned by compile()).
|
| Iterating over this yields the bytecode operations as Instruction instances.
|
| Methods defined here:
|
| __init__(self, x, *, first_line=None, current_offset=None)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self)
|
| __repr__(self)
| Return repr(self).
|
| dis(self)
| Return a formatted view of the bytecode operations.
|
| info(self)
| Return formatted information about the code object.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_traceback(tb) from builtins.type
| Construct a Bytecode from the given traceback
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
" 3 0 LOAD_GLOBAL 0 (print)\n 3 LOAD_CONST 1 ('Hello world')\n 6 CALL_FUNCTION 1 (1 positional, 0 keyword pair)\n 9 POP_TOP\n 10 LOAD_CONST 0 (None)\n 13 RETURN_VALUE\n"
"Name: hello\nFilename: <ipython-input-70-9b74c1c13393>\nArgument count: 0\nKw-only arguments: 0\nNumber of locals: 0\nStack size: 2\nFlags: OPTIMIZED, NEWLOCALS, NOFREE\nConstants:\n 0: None\n 1: 'Hello world'\nNames:\n 0: print"
LOAD_GLOBAL
LOAD_CONST
CALL_FUNCTION
POP_TOP
LOAD_CONST
RETURN_VALUE
3 0 LOAD_GLOBAL 0 (print)
3 LOAD_CONST 1 ('Hello world')
6 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
Help on module opcode:
NAME
opcode
MODULE REFERENCE
https://docs.python.org/3.5/library/opcode
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
DESCRIPTION
opcode module - potentially shared between dis and other modules which
operate on bytecodes (e.g. peephole optimizers).
FUNCTIONS
stack_effect(opcode, oparg=None, /)
Compute the stack effect of the opcode.
DATA
EXTENDED_ARG = 144
HAVE_ARGUMENT = 90
__all__ = ['cmp_op', 'hasconst', 'hasname', 'hasjrel', 'hasjabs', 'has...
cmp_op = ('<', '<=', '==', '!=', '>', '>=', 'in', 'not in', 'is', 'is ...
hascompare = [107]
hasconst = [100]
hasfree = [135, 136, 137, 138, 148]
hasjabs = [111, 112, 113, 114, 115, 119]
hasjrel = [93, 110, 120, 121, 122, 143, 154]
haslocal = [124, 125, 126]
hasname = [90, 91, 95, 96, 97, 98, 101, 106, 108, 109, 116]
hasnargs = [131, 140, 141, 142]
opmap = {'BEFORE_ASYNC_WITH': 52, 'BINARY_ADD': 23, 'BINARY_AND': 64, ...
opname = ['<0>', 'POP_TOP', 'ROT_TWO', 'ROT_THREE', 'DUP_TOP', 'DUP_TO...
FILE
/usr/lib/python3.5/opcode.py
"Name: hello\nFilename: <ipython-input-70-9b74c1c13393>\nArgument count: 0\nKw-only arguments: 0\nNumber of locals: 0\nStack size: 2\nFlags: OPTIMIZED, NEWLOCALS, NOFREE\nConstants:\n 0: None\n 1: 'Hello world'\nNames:\n 0: print"
Name: hello
Filename: <ipython-input-70-9b74c1c13393>
Argument count: 0
Kw-only arguments: 0
Number of locals: 0
Stack size: 2
Flags: OPTIMIZED, NEWLOCALS, NOFREE
Constants:
0: None
1: 'Hello world'
Names:
0: print
Help on function distb in module dis:
distb(tb=None, *, file=None)
Disassemble a traceback (default: last traceback).
2 0 LOAD_CONST 0 (<code object print_hello at 0x7f01fc6fde40, file "string", line 2>)
3 LOAD_CONST 1 ('print_hello')
6 MAKE_FUNCTION 0
9 STORE_NAME 0 (print_hello)
5 12 LOAD_NAME 1 (hello)
15 LOAD_CONST 2 (10)
18 LOAD_CONST 3 (11)
21 CALL_FUNCTION 2 (2 positional, 0 keyword pair)
24 POP_TOP
25 LOAD_CONST 4 (None)
28 RETURN_VALUE
2 0 LOAD_CONST 0 (<code object print_hello at 0x7f01fc6fde40, file "string", line 2>)
3 LOAD_CONST 1 ('print_hello')
6 MAKE_FUNCTION 0
9 STORE_NAME 0 (print_hello)
5 12 LOAD_NAME 1 (hello)
15 LOAD_CONST 2 (10)
18 LOAD_CONST 3 (11)
21 CALL_FUNCTION 2 (2 positional, 0 keyword pair)
24 POP_TOP
25 LOAD_CONST 4 (None)
28 RETURN_VALUE
這兩個function的作用是一樣的
Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=<code object print_hello at 0x7f01fc6f5030, file "<disassembly>", line 2>, argrepr='<code object print_hello at 0x7f01fc6f5030, file "<disassembly>", line 2>', offset=0, starts_line=2, is_jump_target=False)
Instruction(opname='LOAD_CONST', opcode=100, arg=1, argval='print_hello', argrepr="'print_hello'", offset=3, starts_line=None, is_jump_target=False)
Instruction(opname='MAKE_FUNCTION', opcode=132, arg=0, argval=0, argrepr='', offset=6, starts_line=None, is_jump_target=False)
Instruction(opname='STORE_NAME', opcode=90, arg=0, argval='print_hello', argrepr='print_hello', offset=9, starts_line=None, is_jump_target=False)
Instruction(opname='LOAD_NAME', opcode=101, arg=1, argval='hello', argrepr='hello', offset=12, starts_line=5, is_jump_target=False)
Instruction(opname='LOAD_CONST', opcode=100, arg=2, argval=10, argrepr='10', offset=15, starts_line=None, is_jump_target=False)
Instruction(opname='LOAD_CONST', opcode=100, arg=3, argval=11, argrepr='11', offset=18, starts_line=None, is_jump_target=False)
Instruction(opname='CALL_FUNCTION', opcode=131, arg=2, argval=2, argrepr='2 positional, 0 keyword pair', offset=21, starts_line=None, is_jump_target=False)
Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=24, starts_line=None, is_jump_target=False)
Instruction(opname='LOAD_CONST', opcode=100, arg=4, argval=None, argrepr='None', offset=25, starts_line=None, is_jump_target=False)
Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=28, starts_line=None, is_jump_target=False)
(0, 2)
(12, 5)
Help on built-in function stack_effect in module _opcode:
stack_effect(opcode, oparg=None, /)
Compute the stack effect of the opcode.
-1
Help on function findlabels in module dis:
findlabels(code)
Detect all offsets in a byte code which are jump targets.
Return the list of offsets.
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (0)
6 COMPARE_OP 2 (==)
9 POP_JUMP_IF_FALSE 16
3 12 LOAD_CONST 2 (1)
15 RETURN_VALUE
4 >> 16 LOAD_FAST 0 (x)
19 LOAD_CONST 2 (1)
22 COMPARE_OP 2 (==)
25 POP_JUMP_IF_FALSE 32
5 28 LOAD_CONST 3 (2)
31 RETURN_VALUE
>> 32 LOAD_CONST 0 (None)
35 RETURN_VALUE
[16, 32]
['<0>',
'POP_TOP',
'ROT_TWO',
'ROT_THREE',
'DUP_TOP',
'DUP_TOP_TWO',
'<6>',
'<7>',
'<8>',
'NOP',
'UNARY_POSITIVE',
'UNARY_NEGATIVE',
'UNARY_NOT',
'<13>',
'<14>',
'UNARY_INVERT',
'BINARY_MATRIX_MULTIPLY',
'INPLACE_MATRIX_MULTIPLY',
'<18>',
'BINARY_POWER',
'BINARY_MULTIPLY',
'<21>',
'BINARY_MODULO',
'BINARY_ADD',
'BINARY_SUBTRACT',
'BINARY_SUBSCR',
'BINARY_FLOOR_DIVIDE',
'BINARY_TRUE_DIVIDE',
'INPLACE_FLOOR_DIVIDE',
'INPLACE_TRUE_DIVIDE',
'<30>',
'<31>',
'<32>',
'<33>',
'<34>',
'<35>',
'<36>',
'<37>',
'<38>',
'<39>',
'<40>',
'<41>',
'<42>',
'<43>',
'<44>',
'<45>',
'<46>',
'<47>',
'<48>',
'<49>',
'GET_AITER',
'GET_ANEXT',
'BEFORE_ASYNC_WITH',
'<53>',
'<54>',
'INPLACE_ADD',
'INPLACE_SUBTRACT',
'INPLACE_MULTIPLY',
'<58>',
'INPLACE_MODULO',
'STORE_SUBSCR',
'DELETE_SUBSCR',
'BINARY_LSHIFT',
'BINARY_RSHIFT',
'BINARY_AND',
'BINARY_XOR',
'BINARY_OR',
'INPLACE_POWER',
'GET_ITER',
'GET_YIELD_FROM_ITER',
'PRINT_EXPR',
'LOAD_BUILD_CLASS',
'YIELD_FROM',
'GET_AWAITABLE',
'<74>',
'INPLACE_LSHIFT',
'INPLACE_RSHIFT',
'INPLACE_AND',
'INPLACE_XOR',
'INPLACE_OR',
'BREAK_LOOP',
'WITH_CLEANUP_START',
'WITH_CLEANUP_FINISH',
'RETURN_VALUE',
'IMPORT_STAR',
'<85>',
'YIELD_VALUE',
'POP_BLOCK',
'END_FINALLY',
'POP_EXCEPT',
'STORE_NAME',
'DELETE_NAME',
'UNPACK_SEQUENCE',
'FOR_ITER',
'UNPACK_EX',
'STORE_ATTR',
'DELETE_ATTR',
'STORE_GLOBAL',
'DELETE_GLOBAL',
'<99>',
'LOAD_CONST',
'LOAD_NAME',
'BUILD_TUPLE',
'BUILD_LIST',
'BUILD_SET',
'BUILD_MAP',
'LOAD_ATTR',
'COMPARE_OP',
'IMPORT_NAME',
'IMPORT_FROM',
'JUMP_FORWARD',
'JUMP_IF_FALSE_OR_POP',
'JUMP_IF_TRUE_OR_POP',
'JUMP_ABSOLUTE',
'POP_JUMP_IF_FALSE',
'POP_JUMP_IF_TRUE',
'LOAD_GLOBAL',
'<117>',
'<118>',
'CONTINUE_LOOP',
'SETUP_LOOP',
'SETUP_EXCEPT',
'SETUP_FINALLY',
'<123>',
'LOAD_FAST',
'STORE_FAST',
'DELETE_FAST',
'<127>',
'<128>',
'<129>',
'RAISE_VARARGS',
'CALL_FUNCTION',
'MAKE_FUNCTION',
'BUILD_SLICE',
'MAKE_CLOSURE',
'LOAD_CLOSURE',
'LOAD_DEREF',
'STORE_DEREF',
'DELETE_DEREF',
'<139>',
'CALL_FUNCTION_VAR',
'CALL_FUNCTION_KW',
'CALL_FUNCTION_VAR_KW',
'SETUP_WITH',
'EXTENDED_ARG',
'LIST_APPEND',
'SET_ADD',
'MAP_ADD',
'LOAD_CLASSDEREF',
'BUILD_LIST_UNPACK',
'BUILD_MAP_UNPACK',
'BUILD_MAP_UNPACK_WITH_CALL',
'BUILD_TUPLE_UNPACK',
'BUILD_SET_UNPACK',
'SETUP_ASYNC_WITH',
'<155>',
'<156>',
'<157>',
'<158>',
'<159>',
'<160>',
'<161>',
'<162>',
'<163>',
'<164>',
'<165>',
'<166>',
'<167>',
'<168>',
'<169>',
'<170>',
'<171>',
'<172>',
'<173>',
'<174>',
'<175>',
'<176>',
'<177>',
'<178>',
'<179>',
'<180>',
'<181>',
'<182>',
'<183>',
'<184>',
'<185>',
'<186>',
'<187>',
'<188>',
'<189>',
'<190>',
'<191>',
'<192>',
'<193>',
'<194>',
'<195>',
'<196>',
'<197>',
'<198>',
'<199>',
'<200>',
'<201>',
'<202>',
'<203>',
'<204>',
'<205>',
'<206>',
'<207>',
'<208>',
'<209>',
'<210>',
'<211>',
'<212>',
'<213>',
'<214>',
'<215>',
'<216>',
'<217>',
'<218>',
'<219>',
'<220>',
'<221>',
'<222>',
'<223>',
'<224>',
'<225>',
'<226>',
'<227>',
'<228>',
'<229>',
'<230>',
'<231>',
'<232>',
'<233>',
'<234>',
'<235>',
'<236>',
'<237>',
'<238>',
'<239>',
'<240>',
'<241>',
'<242>',
'<243>',
'<244>',
'<245>',
'<246>',
'<247>',
'<248>',
'<249>',
'<250>',
'<251>',
'<252>',
'<253>',
'<254>',
'<255>']
[('POP_TOP', 1),
('ROT_TWO', 2),
('ROT_THREE', 3),
('DUP_TOP', 4),
('DUP_TOP_TWO', 5),
('NOP', 9),
('UNARY_POSITIVE', 10),
('UNARY_NEGATIVE', 11),
('UNARY_NOT', 12),
('UNARY_INVERT', 15),
('BINARY_MATRIX_MULTIPLY', 16),
('INPLACE_MATRIX_MULTIPLY', 17),
('BINARY_POWER', 19),
('BINARY_MULTIPLY', 20),
('BINARY_MODULO', 22),
('BINARY_ADD', 23),
('BINARY_SUBTRACT', 24),
('BINARY_SUBSCR', 25),
('BINARY_FLOOR_DIVIDE', 26),
('BINARY_TRUE_DIVIDE', 27),
('INPLACE_FLOOR_DIVIDE', 28),
('INPLACE_TRUE_DIVIDE', 29),
('GET_AITER', 50),
('GET_ANEXT', 51),
('BEFORE_ASYNC_WITH', 52),
('INPLACE_ADD', 55),
('INPLACE_SUBTRACT', 56),
('INPLACE_MULTIPLY', 57),
('INPLACE_MODULO', 59),
('STORE_SUBSCR', 60),
('DELETE_SUBSCR', 61),
('BINARY_LSHIFT', 62),
('BINARY_RSHIFT', 63),
('BINARY_AND', 64),
('BINARY_XOR', 65),
('BINARY_OR', 66),
('INPLACE_POWER', 67),
('GET_ITER', 68),
('GET_YIELD_FROM_ITER', 69),
('PRINT_EXPR', 70),
('LOAD_BUILD_CLASS', 71),
('YIELD_FROM', 72),
('GET_AWAITABLE', 73),
('INPLACE_LSHIFT', 75),
('INPLACE_RSHIFT', 76),
('INPLACE_AND', 77),
('INPLACE_XOR', 78),
('INPLACE_OR', 79),
('BREAK_LOOP', 80),
('WITH_CLEANUP_START', 81),
('WITH_CLEANUP_FINISH', 82),
('RETURN_VALUE', 83),
('IMPORT_STAR', 84),
('YIELD_VALUE', 86),
('POP_BLOCK', 87),
('END_FINALLY', 88),
('POP_EXCEPT', 89),
('STORE_NAME', 90),
('DELETE_NAME', 91),
('UNPACK_SEQUENCE', 92),
('FOR_ITER', 93),
('UNPACK_EX', 94),
('STORE_ATTR', 95),
('DELETE_ATTR', 96),
('STORE_GLOBAL', 97),
('DELETE_GLOBAL', 98),
('LOAD_CONST', 100),
('LOAD_NAME', 101),
('BUILD_TUPLE', 102),
('BUILD_LIST', 103),
('BUILD_SET', 104),
('BUILD_MAP', 105),
('LOAD_ATTR', 106),
('COMPARE_OP', 107),
('IMPORT_NAME', 108),
('IMPORT_FROM', 109),
('JUMP_FORWARD', 110),
('JUMP_IF_FALSE_OR_POP', 111),
('JUMP_IF_TRUE_OR_POP', 112),
('JUMP_ABSOLUTE', 113),
('POP_JUMP_IF_FALSE', 114),
('POP_JUMP_IF_TRUE', 115),
('LOAD_GLOBAL', 116),
('CONTINUE_LOOP', 119),
('SETUP_LOOP', 120),
('SETUP_EXCEPT', 121),
('SETUP_FINALLY', 122),
('LOAD_FAST', 124),
('STORE_FAST', 125),
('DELETE_FAST', 126),
('RAISE_VARARGS', 130),
('CALL_FUNCTION', 131),
('MAKE_FUNCTION', 132),
('BUILD_SLICE', 133),
('MAKE_CLOSURE', 134),
('LOAD_CLOSURE', 135),
('LOAD_DEREF', 136),
('STORE_DEREF', 137),
('DELETE_DEREF', 138),
('CALL_FUNCTION_VAR', 140),
('CALL_FUNCTION_KW', 141),
('CALL_FUNCTION_VAR_KW', 142),
('SETUP_WITH', 143),
('EXTENDED_ARG', 144),
('LIST_APPEND', 145),
('SET_ADD', 146),
('MAP_ADD', 147),
('LOAD_CLASSDEREF', 148),
('BUILD_LIST_UNPACK', 149),
('BUILD_MAP_UNPACK', 150),
('BUILD_MAP_UNPACK_WITH_CALL', 151),
('BUILD_TUPLE_UNPACK', 152),
('BUILD_SET_UNPACK', 153),
('SETUP_ASYNC_WITH', 154)]
114
而這些bytecode被定義在opcode module中
('<',
'<=',
'==',
'!=',
'>',
'>=',
'in',
'not in',
'is',
'is not',
'exception match',
'BAD')
[100]
[135, 136, 137, 138, 148]
[90, 91, 95, 96, 97, 98, 101, 106, 108, 109, 116]
[93, 110, 120, 121, 122, 143, 154]
[111, 112, 113, 114, 115, 119]
[124, 125, 126]
[107]
Python dis module
https://docs.python.org/3.7/library/dis.html?module-dis
stack overflow 對於比較exec和eval的回答
Python/ceval.c
python interpreter main的進入點
python interpreter initiali
PyFrameObject
Include/frameobject.h
2017-08-25 12:30:51
In CPython, the compilation from source code to bytecode involves several steps:
Parser/
Python/
Python-ast.c
Creates C structs corresponding to the ASDL types. Also contains code for marshalling AST nodes (core ASDL types have marshalling code in asdl.c). “File automatically generated by Parser/asdl_c.py”. This file must be committed separately after every grammar change is committed since the version value is set to the latest grammar change revision number.
asdl.c
Contains code to handle the ASDL sequence type. Also has code to handle marshalling the core ASDL types, such as number and identifier. Used by Python-ast.c for marshalling AST nodes.
ast.c
Converts Python’s parse tree into the abstract syntax tree.
ceval.c
Executes byte code (aka, eval loop).
compile.c
Emits bytecode based on the AST.
symtable.c
Generates a symbol table from AST.
pyarena.c
Implementation of the arena memory manager.
import.c
Home of the magic number (named MAGIC) for bytecode versioning
Include/
Python-ast.h
Contains the actual definitions of the C structs as generated by Python/Python-ast.c. “Automatically generated by Parser/asdl_c.py”.
asdl.h
Header for the corresponding Python/ast.c.
ast.h
Declares PyAST_FromNode() external (from Python/ast.c).
code.h
Header file for Objects/codeobject.c; contains definition of PyCodeObject.
symtable.h
Header for Python/symtable.c. struct symtable and PySTEntryObject are defined here.
pyarena.h
Header file for the corresponding Python/pyarena.c.
opcode.h
Master list of bytecode; if this file is modified you must modify several other files accordingly (see “Introducing New Bytecode”)
Objects/
Lib/
https://docs.python.org/devguide/compiler.html
http://blog.csdn.net/zhsenl/article/category/2307109/1
https://leanpub.com/insidethepythonvirtualmachine/read#leanpub-auto-the-block-stack
python pyc