An introduction to Python bytecode
Python is described as an interpreted language. The source code is translated into native CPU instructions as the program runs, but this is not fully correct only partially correct. Like python many interpreted languages javascript, Perl, BASIC, forth actually compiles the source code into a set of instructions for a virtual machine. And the Python interpreter is an implementation of that virtual machine and this intermediate format is called “bytecode.”
In Python probably used to seeing python source code files, they have a file extension with.py
And you may also have seen another type of file, which have file extension with .pyc. Those .pyc files Python leaves lying around aren't just some "faster" or "optimized" version of source code, they're the bytecode instructions that will be executed by Python's virtual machine asthe program runs.
To
Accessing and understanding, Python bytecode the dis
module used from the Python standard library. dis
module provides a “disassembler” for Python bytecode,
making it easy to get a readable version and look up the various
bytecode instructions. ‘import dis’ is used import the module and
the function dis.dis()
will disassemble the function, method, class, module, compiled code
object, or a string literal containing source code and print a
human-readable version. Another handy function is distb()
in the dis module
.
we can pass it a Python traceback object or call it after an
exception has been raised, and it will disassemble the topmost
function on the call stack at the time of the exception, print its
bytecode, and ithen nsert a pointer to the instruction that raised
the exception.
Code objects represent blocks of bytecode and are accessible as the attribute on__code__
the function and according to the Python documentation, there are three types of blocks or namespaces: a module, a function body, and a class definition. Such objects are produced whenever a block of code is compiled, e.g., at the startup or during execution time.
Few
list important attributes are:-co_consts
is
the tuple of constants used in the bytecode,co_varnames
is the tuple of names of arguments and local variables,
co_names
is the tuple of names of local variables,co_code is the string of raw
compiled bytecode