DEV Community

Discussion on: Is Python compiled or interpreted?

Collapse
 
michaelcurrin profile image
Michael Currin • Edited

Hi, here is my input on the topic, from my python background.

Based on this article, Python has both compiled and interpreted parts to it. But the compiled part is minor I think and its still useful to think of Python and interpreted

geeksforgeeks.org/python-compiled-...

Yes Python does compile to .pyc files. They are not used immediately - they are only used when running the application a second time and if the modified date of the .py and .pyc file is the same then it does not recompile the files. So performance is a bit faster on repeat runs. (If you view your .pyc file it will look garbled to you but docstrings actually get preserved as plain text, for interest)

These files are only created when doing module imports (python - m foo or imports within a script) and not when running a script directly (python foo.py). You can also give the python command a flag to disable creating .pyc files.

Yes those byte code .pyc files are compiled files but they still get sent to the python interpreter as machine code. So .pyc files only get us partway there.

Using .pyc files improves performance a bit. But those compiled files will not give you the performance of true compiled languages like C or C++ or Rust.

This is a complex topic. I always thought Java must be compiled because it won't compile if you have bad types, you get compiled files out and you get performance close to C. But the thing is that Java creates byte code when is then interpreted by the JVM (Java Virtual Machine) to machine code and run.

This article covers Java Interpreter Compiler. Note the diagram from high level to byte code to machine code
codespeedy.com/why-java-is-called-...

I don't know about Java anymore - is it both compile and interpreted? Python compiled step is optional and it doesnt have compile time checks so I'd say Python is interpreted. But I don't know how the actual interpreter works to discuss further

Collapse
 
amritanshupandey profile image
Amritanshu Pandey

Very thorough explanation! Thanks!

Collapse
 
ayushbasak profile image
Ayush Basak

Thanks! I learned something new. 😀

Collapse
 
michaelcurrin profile image
Michael Currin • Edited

Oh and if you want something like compile time type checks for python, to match C and Java, have a look at Mypy.

From python 3.5 you can use optional type annotations in code and use the mypy command to validate them.

michaelcurrin.github.io/code-cookb...

It is a similar principle to TypeScript adding safety to JS code types. Except here we don't convert
.ts to .js files we just stay on .py files and types get ignored at runtime of your application (ie when MyPy is done running)