Convert Figma logo to code with AI

oracle logograalpython

GraalPy – A high-performance embeddable Python 3 runtime for Java

1,339
117
1,339
51

Top Related Projects

GraalPy – A high-performance embeddable Python 3 runtime for Java

1,294

PyPy is a very fast and compliant implementation of the Python language.

10,303

NumPy aware dynamic Python compiler using LLVM

MicroPython - a lean and efficient Python implementation for microcontrollers and constrained systems

A Python Interpreter written in Rust

Implementation of Python 3.x for .NET Framework that is built on top of the Dynamic Language Runtime.

Quick Overview

GraalPython is an implementation of Python on the GraalVM, a universal virtual machine for running applications written in JavaScript, Python, Ruby, R, JVM-based languages, and LLVM-based languages. It aims to provide high performance and interoperability with other GraalVM languages while maintaining compatibility with CPython.

Pros

  • High performance due to GraalVM's advanced JIT compilation
  • Seamless interoperability with other GraalVM languages (Java, JavaScript, R, etc.)
  • Ability to create native executables for faster startup and lower memory footprint
  • Access to Java libraries and ecosystem

Cons

  • Not 100% compatible with all CPython libraries and extensions
  • Still in development, with some features missing or incomplete
  • Potential learning curve for developers unfamiliar with GraalVM
  • Limited community support compared to CPython

Code Examples

  1. Basic Python script:
# hello.py
print("Hello, GraalPython!")
  1. Interoperability with Java:
import java
from java.util import ArrayList

list = ArrayList()
list.add("GraalPython")
list.add("Java")
print(list)
  1. Using GraalVM's polyglot capabilities:
import polyglot

js_code = """
function greet(name) {
    return `Hello, ${name}!`;
}
"""

polyglot.eval(language="js", string=js_code)
result = polyglot.eval(language="js", string="greet('GraalPython')")
print(result)

Getting Started

  1. Install GraalVM (version 22.3.0 or later) from https://www.graalvm.org/downloads/
  2. Set JAVA_HOME to point to your GraalVM installation
  3. Install GraalPython using GraalVM Updater:
gu install python
  1. Run a Python script:
graalpython hello.py

For more advanced usage and configuration options, refer to the official GraalPython documentation.

Competitor Comparisons

GraalPy – A high-performance embeddable Python 3 runtime for Java

Pros of GraalPython

  • High-performance Python implementation on the GraalVM
  • Seamless interoperability with other GraalVM languages
  • Supports both JIT and AOT compilation for improved execution speed

Cons of GraalPython

  • Limited compatibility with some Python libraries and frameworks
  • Smaller community and ecosystem compared to CPython
  • May require additional configuration for optimal performance

Code Comparison

GraalPython:

import polyglot

def greet(name):
    return polyglot.eval(language="js", string=f"'Hello, ' + '{name}'")

print(greet("World"))

CPython:

def greet(name):
    return f"Hello, {name}"

print(greet("World"))

The GraalPython example showcases its polyglot capabilities, allowing seamless integration with JavaScript. The CPython example demonstrates the standard Python syntax for string formatting and function definition.

Both implementations aim to provide a Python runtime environment, but GraalPython focuses on performance and interoperability within the GraalVM ecosystem, while CPython serves as the reference implementation with broader compatibility and community support.

1,294

PyPy is a very fast and compliant implementation of the Python language.

Pros of PyPy

  • Longer history and more mature project with extensive community support
  • Generally faster execution for long-running Python programs
  • Better compatibility with existing Python libraries and frameworks

Cons of PyPy

  • Limited support for Python 3.9+ versions
  • Slower startup time compared to GraalPython
  • Less integration with other languages and runtimes

Code Comparison

PyPy:

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(10))

GraalPython:

@jit
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(10))

The main difference is that GraalPython allows for easy JIT compilation using the @jit decorator, which can potentially improve performance for frequently executed functions.

Both PyPy and GraalPython aim to improve Python performance, but they take different approaches. PyPy uses a JIT compiler and is more focused on pure Python execution, while GraalPython leverages the GraalVM ecosystem for polyglot capabilities and integration with other languages. The choice between them depends on specific project requirements and use cases.

10,303

NumPy aware dynamic Python compiler using LLVM

Pros of Numba

  • Specialized for numerical and scientific computing, offering significant performance improvements for NumPy-based code
  • Easier integration with existing Python codebases, as it works as a JIT compiler for Python functions
  • More mature project with a larger community and ecosystem

Cons of Numba

  • Limited to a subset of Python and NumPy features, not a full Python implementation
  • May require code modifications to achieve optimal performance
  • Less flexible for general-purpose Python acceleration compared to GraalPython

Code Comparison

GraalPython example:

# GraalPython automatically optimizes Python code
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

Numba example:

from numba import jit

@jit(nopython=True)
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

In this comparison, GraalPython optimizes the function automatically, while Numba requires the @jit decorator to enable compilation. Both approaches can significantly improve performance for numerical computations, but Numba's optimization is more explicit and tailored for numerical workloads.

MicroPython - a lean and efficient Python implementation for microcontrollers and constrained systems

Pros of MicroPython

  • Designed for microcontrollers and embedded systems, offering a smaller footprint
  • Extensive hardware support and libraries for various microcontroller boards
  • Active community with frequent updates and contributions

Cons of MicroPython

  • Limited standard library compared to CPython
  • Performance may be slower for complex computations
  • Less compatible with existing Python packages and libraries

Code Comparison

MicroPython:

import machine
import time

led = machine.Pin(2, machine.Pin.OUT)
while True:
    led.toggle()
    time.sleep_ms(500)

GraalPython:

import time

while True:
    print("Hello, GraalPython!")
    time.sleep(1)

Key Differences

  • MicroPython focuses on embedded systems, while GraalPython aims for high-performance Python execution on the JVM
  • GraalPython offers better integration with Java ecosystems and libraries
  • MicroPython provides direct hardware access and control, which is not a primary focus of GraalPython
  • GraalPython generally has better performance for complex computations and larger applications
  • MicroPython has a smaller memory footprint, making it suitable for resource-constrained devices

A Python Interpreter written in Rust

Pros of RustPython

  • Written in Rust, offering memory safety and performance benefits
  • Designed as a standalone Python implementation, potentially more flexible for embedding
  • Active community-driven development with frequent updates

Cons of RustPython

  • Less mature and feature-complete compared to GraalPython
  • May lack some of the advanced optimizations present in GraalVM

Code Comparison

RustPython:

use rustpython_vm as vm;

fn main() {
    vm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
        let scope = vm.new_scope_with_builtins();
        let code = vm.compile("print('Hello, World!')", "example.py", vm::compiler::Mode::Exec).unwrap();
        vm.run_code_obj(code, scope).unwrap();
    });
}

GraalPython:

import org.graalvm.polyglot.*;

public class HelloWorld {
    public static void main(String[] args) {
        try (Context context = Context.create("python")) {
            context.eval("python", "print('Hello, World!')");
        }
    }
}

Both implementations aim to provide Python functionality, but RustPython focuses on a standalone Rust-based interpreter, while GraalPython leverages the GraalVM ecosystem for polyglot capabilities and performance optimizations.

Implementation of Python 3.x for .NET Framework that is built on top of the Dynamic Language Runtime.

Pros of IronPython3

  • Better integration with .NET ecosystem and libraries
  • More mature and stable implementation for Windows environments
  • Supports Python 3 syntax and features

Cons of IronPython3

  • Limited cross-platform support compared to GraalPython
  • Slower performance for pure Python code execution
  • Less frequent updates and maintenance

Code Comparison

IronPython3:

import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import MessageBox
MessageBox.Show("Hello from IronPython!")

GraalPython:

import java
from java.awt import JOptionPane
JOptionPane.showMessageDialog(None, "Hello from GraalPython!")

The code examples demonstrate the integration capabilities of each implementation with their respective ecosystems (.NET for IronPython3 and Java for GraalPython). IronPython3 uses the clr module to interact with .NET libraries, while GraalPython leverages Java interoperability to access Java classes directly.

Both implementations aim to provide Python compatibility within their respective environments, but they differ in their target platforms and integration focus. IronPython3 is more suited for Windows and .NET development, while GraalPython offers better performance and cross-platform support within the GraalVM ecosystem.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

GraalPy, the GraalVM Implementation of Python

Join Slack GraalVM on Twitter License

GraalPy is a high-performance implementation of the Python language for the JVM built on GraalVM. GraalPy is a Python 3.11 compliant runtime. It has first-class support for embedding in Java and can turn Python applications into fast, standalone binaries. GraalPy is ready for production running pure Python code and has experimental support for many popular native extension modules.

Why GraalPy?

Low-overhead integration with Java and other languages

Compatible with the Python ecosystem

  • Use almost any standard Python feature, the CPython tests run on every commit and pass ~85%
  • See if the packages you need work according to our Python Compatibility Checker
  • Support for native extension modules is considered experimental, but you can already install packages like NumPy, PyTorch, or Tensorflow; run Hugging Face models like Stable Diffusion or GPT We run the tests of the most depended on PyPI packages every day. For 97% of those packages a recent version can be installed on GraalPy and GraalPy passes over 60% of all tests of all packages combined. We assume that CPython not passing 100% of all tests is due to problems in our infrastructure that may also affect GraalPy. Packages where CPython fails all tests are marked as "not tested" for both CPython and GraalPy.

Runs Python code faster

  • Pure Python code is often faster than on CPython after JIT compilation
  • C extension performance is near CPython, but varies depending on the specific interactions of native and Python code
  • GraalPy is ~4x faster than CPython on the official Python Performance Benchmark Suite Benchmarks run via pip install pyperformance && pyperformance run on each of CPython and GraalPy. Harness and benchmarks were adapted by hand for Jython due to missing Python 3 support. Each interpreter was installed via pyenv. Geomean speedup was calculated against CPython on the intersection of benchmarks that run on all interpreters.

Getting Started

Embedding GraalPy in Java

GraalPy is available on Maven Central for inclusion in Java projects. Refer to our embedding documentation for more details.

  • Maven

    <dependency>
        <groupId>org.graalvm.polyglot</groupId>
        <artifactId>polyglot</artifactId>
        <version>24.1.2</version>
    </dependency>
    <dependency>
        <groupId>org.graalvm.polyglot</groupId>
        <artifactId>python</artifactId>
        <version>24.1.2</version>
        <type>pom</type>
    </dependency>
    
  • Gradle

    implementation("org.graalvm.polyglot:polyglot:24.1.2")
    implementation("org.graalvm.polyglot:python:24.1.2")
    
Replacing CPython with GraalPy

GraalPy should in many cases work as a drop-in replacement for CPython. You can use pip to install packages as usual. Packages with C code usually do not provide binaries for GraalPy, so they will be automatically compiled during installation. This means that build tools have to be available and installation will take longer. We provide Github actions to help you build binary packages with the correct dependencies. Thanks to our integration with GraalVM Native Image, we can deploy Python applications as standalone binary, all dependencies included.

  • Linux

    The easiest way to install GraalPy on Linux is to use Pyenv (the Python version manager). To install version 24.1.2 using Pyenv, run the following commands:

    pyenv install graalpy-24.1.2
    
    pyenv shell graalpy-24.1.2
    

    NOTE: There will be a delay between GraalPy release and its availability on Pyenv. Make sure to update Pyenv.

    Alternatively, you can download a compressed GraalPy installation file from GitHub releases.

    1. Find the download that matches the pattern graalpy-XX.Y.Z-linux-amd64.tar.gz or graalpy-XX.Y.Z-linux-aarch64.tar.gz (depending on your platform) and download.
    2. Uncompress the file and update your PATH environment variable to include the graalpy-XX.Y.Z-linux-amd64/bin (or graalpy-XX.Y.Z-linux-aarch64/bin) directory.
  • macOS

    The easiest way to install GraalPy on macOS is to use Pyenv (the Python version manager). To install version 24.1.2 using Pyenv, run the following commands:

    pyenv install graalpy-24.1.2
    
    pyenv shell graalpy-24.1.2
    

    NOTE: There will be a delay between GraalPy release and its availability on Pyenv. Make sure to update Pyenv.

    Alternatively, you can download a compressed GraalPy installation file from GitHub releases.

    1. Find the download that matches the pattern graalpy-XX.Y.Z-macos-amd64.tar.gz or graalpy-XX.Y.Z-macos-aarch64.tar.gz (depending on your platform) and download.
    2. Remove the quarantine attribute.
      sudo xattr -r -d com.apple.quarantine /path/to/graalpy
      
      For example:
      sudo xattr -r -d com.apple.quarantine ~/.pyenv/versions/graalpy-24.1.2
      
    3. Uncompress the file and update your PATH environment variable to include to the graalpy-XX.Y.Z-macos-amd64/bin (or graalpy-XX.Y.Z-macos-aarch64/bin) directory.
  • Windows

    The Windows support of GraalPy is still experimental, so not all features and packages may be available. The easiest way to install GraalPy on Windows is to use Pyenv-win (the Python version manager for Windows). To install version 24.1.2 using Pyenv-win, run the following commands:

    pyenv install graalpy-24.1.2-windows-amd64
    
    pyenv shell graalpy-24.1.2-windows-amd64
    

    NOTE: There will be a delay between GraalPy release and its availability on Pyenv. Make sure to update Pyenv.

    Alternatively, you can download a compressed GraalPy installation file from GitHub releases.

    1. Find the download that matches the pattern graalpy-XX.Y.Z-windows-amd64.tar.gz and download.
    2. Uncompress the file and update your PATH variable to include to the graalpy-XX.Y.Z-windows-amd64/bin directory.
Using GraalPy in Github Actions

The setup-python action supports GraalPy:

    - name: Setup GraalPy
      uses: actions/setup-python@v5
      with:
        python-version: graalpy # or graalpy24.1 to pin a version
Migrating Jython Scripts to GraalPy

Most existing Jython code that uses Java integration will be based on a stable Jython release—however, these are only available in Python 2.x versions. To migrate your code from Python 2 to Python 3, follow the official guide from the Python community. GraalPy provides a special mode to facilitate migration. To run Jython scripts, you need to use a GraalPy distribution running on the JVM so you can access Java classes from Python scripts.

  • Linux

    1. Find and download a compressed GraalPy installation file from GitHub releases that matches the pattern graalpy-jvm-XX.Y.Z-linux-amd64.tar.gz or graalpy-jvm-XX.Y.Z-linux-aarch64.tar.gz (depending on your platform) and download.
    2. Uncompress the file and update your PATH environment variable to include the graalpy-jvm-XX.Y.Z-linux-amd64/bin (or graalpy-jvm-XX.Y.Z-linux-aarch64/bin) directory.
    3. Run your scripts with graalpy --python.EmulateJython.
  • macOS

    1. Find and download a compressed GraalPy installation file from GitHub releases that matches the pattern graalpy-jvm-XX.Y.Z-macos-amd64.tar.gz or graalpy-jvm-XX.Y.Z-macos-aarch64.tar.gz (depending on your platform) and download.
    2. Remove the quarantine attribute.
      sudo xattr -r -d com.apple.quarantine /path/to/graalpy
      
      For example:
      sudo xattr -r -d com.apple.quarantine ~/.pyenv/versions/graalpy-24.1.2
      
    3. Uncompress the file and update your PATH environment variable to include to the graalpy-jvm-XX.Y.Z-macos-amd64/bin (or graalpy-jvm-XX.Y.Z-macos-aarch64/bin) directory.
    4. Run your scripts with graalpy --python.EmulateJython.
  • Windows

    1. Find and download a compressed GraalPy installation file from GitHub releases that matches the pattern graalpy-jvm-XX.Y.Z-windows-amd64.tar.gz.
    2. Uncompress the file and update your PATH variable to include to the graalpy-jvm-XX.Y.Z-windows-amd64/bin directory.
    3. Run your scripts with graalpy --python.EmulateJython.

Examples

Java AWT app with Python graph library using JBang  |  Standalone binary of a Python game by Joey Navarro with all dependencies included.

Documentation

GraalPy Quick Reference Sheet should help you get started. More GraalPy-specific user documentation is available in docs/user. General documentation about polyglot programming and language embedding is available on the GraalVM website.

Community

The best way to get in touch with us is to join the #graalpy channel on GraalVM Slack or tweet us.

Contributing

This project welcomes contributions from the community. Before submitting a pull request, please review our contribution guide.

If you're thinking about contributing something to this repository, you will need to sign the Oracle Contributor Agreement for us to able to merge your work. Also take a look at the code of conduct for contributors.

Security

Consult the security guide for our responsible security vulnerability disclosure process.

License

This GraalVM implementation of Python is Copyright (c) 2017, 2024 Oracle and/or its affiliates and is made available to you under the terms the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/. This implementation is in part derived from and contains additional code from 3rd parties, the copyrights and licensing of which is detailed in the LICENSE and THIRD_PARTY_LICENSE files.