Is python a interpreted or compiled language?

Ian Kelly ian.g.kelly at gmail.com
Wed Jun 20 20:27:53 EDT 2012


On Wed, Jun 20, 2012 at 5:30 PM, gmspro <gmspro at yahoo.com> wrote:
>
> Hi,
>
> Is python a interpreted or compiled language?

Like other languages that use a VM bytecode, it's a little bit of
both.  The actual Python code is compiled into Python bytecode.  The
bytecode is interpreted.

> What does happen after this command: python f.py
>
> I knew python makes file.pyc file to store the bytecode. For java , .class
> file is the bytecode file, someone can run that file from any machine. So is
> the .pyc file executale like java?

Yes, Python is (mostly) able to run the .pyc file directly without the
.py source (although tracebacks will be a bit less informative if the
.py is not available).

I say "mostly" because, while the bytecode is cross-platform, it is
version dependent.  A Python 3.x installation may or may not be able
to run a bytecode compiled by Python 3.y.

> Can anyone please explain/elaborate the process/order of executing python
> file with example?

Whenever a Python module is imported, the interpreter first checks
whether a .pyc is available that has the appropriate "magic number"
and is up-to-date (based on its timestamp compared to the
corresponding .py file).  If it can't find or can't use the .pyc file,
then it recompiles the .py file into a .pyc file.  Otherwise, it skips
the compilation step and just runs the bytecode from the .pyc file.

Note though that when a .py file is executed directly (not imported),
it does not look for or generate a .pyc file; it just compiles the .py
unconditionally in memory and runs the bytecode.

If you're interested in the bytecode, you can use the dis module to
disassemble functions and other code objects and examine it:

>>> import dis
>>> def f(x):
...     return x + 1
...
>>> dis.dis(f)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (1)
              6 BINARY_ADD
              7 RETURN_VALUE

Cheers,
Ian



More information about the Python-list mailing list