Python is one of the most popular programming languages among developers, but it has certain limitations. For example, depending on the application, it can be up to 100 times as slow as some lower-level languages. That’s why many companies rewrite their applications in another language once Python’s speed becomes a bottleneck for users. But what if there was a way to keep Python’s awesome features and improve its speed? Enter PyPy.
PyPy is a very compliant Python interpreter that is a worthy alternative to CPython 2.7, 3.6, and soon 3.7. By installing and running your application with it, you can gain noticeable speed improvements. How much of an improvement you’ll see depends on the application you’re running.
In this tutorial, you’ll learn:
- How to install and run your code with PyPy
- How PyPy compares with CPython in terms of speed
- What PyPy’s features are and how they make your Python code run faster
- What PyPy’s limitations are
The examples in this tutorial use Python 3.6 since that’s the latest version of Python that PyPy is compatible with.
CPython is the original implementation of Python and is by far the most popular and most maintained. When people refer to Python, they more often than not mean CPython. You’re probably using CPython right now!
However, because it’s a high-level interpreted language, CPython has certain limitations and won’t win any medals for speed. That’s where PyPy can come in handy. Since it adheres to the Python language specification, PyPy requires no change in your codebase and can offer significant speed improvements thanks to the features you’ll see below.
Now, you may be wondering why CPython doesn’t implement PyPy’s awesome features if they use the same syntax. The reason is that implementing those features would require huge changes to the source code and would be a major undertaking.
Without diving too much into theory, let’s see PyPy in action.
Your OS may already provide a PyPy package. On macOS, for example, you can install it with the help of Homebrew:
$ brew install pypy3
If not, you can download a prebuilt binary for your OS and architecture. Once you complete the download, it’s just a matter of unpacking the tarball or ZIP file. Then you can execute PyPy without needing to install it anywhere:
$ tar xf pypy3.6-v7.3.1-osx64.tar.bz2 $ ./pypy3.6-v7.3.1-osx64/bin/pypy3 Python 3.6.9 (?, Jul 19 2020, 21:37:06) [PyPy 7.3.1 with GCC 4.2.1] Type "help", "copyright", "credits" or "license" for more information.
Before executing the code above, you need to be inside the folder where you downloaded the binary. Refer to the installation documentation for the complete instructions.
You now have PyPy installed and you’re ready to see it in action! To do that, create a Python file called
script.py and put the following code in it: