Annotation Interface GraalPyModule


@Introduction @Bean @Target(TYPE) @Retention(RUNTIME) public @interface GraalPyModule
An annotation for Micronaut Introduction Advice that implements this interface using the GraalPy Python implementation and the polyglot type mapping.

Global state: there is a single shared polyglot Context that the advice uses to import the Python modules annotated with GraalPyModule and execute their Python code. If multiple GraalPyModule annotations map to the same Python module, they will all delegate to the same underlying Python module object.

Python configuration: the default Python context configuration can be altered by implementing GraalPyContextBuilderFactory.

Threading: the Python modules exposed to Java using this annotation can be accessed from multiple threads in parallel. On the Python side different Java threads will appear as different Python level threads.

Scalability: for compatibility reasons, the Python engine internally serializes multithreaded execution of Python code using the global interpreter lock and therefore there is only one thread executing Python code at a time. (Note: individual threads take turns after fixed time quantum in a round-robin fashion).

If better utilization of multicore hardware is required, one can use multiple polyglot contexts. Each context represents an isolated self-contained Python engine and has its own "global" interpreter lock. The caveats are:

  • Native Python extensions, such as NumPy, are currently not supported in multi-context mode.
  • Python polyglot contexts are not cheap to create and should be pooled.
  • There are caveats when sharing Python objects between contexts. It is recommended to avoid this if possible. More details.

Currently, this Introduction Advice does not support multi-context execution, but users can implement it by hand using the Context APIs directly. We are collecting feedback and requirements to provide such features in the next versions.

Deployment: for the ease of installation and deployment of 3rd party Python packages as well as custom Python scripts or packages, it is recommended to use the GraalPy Maven plugin. The polyglot context is automatically configured to include the resources configured in the plugin.

Example: python module hello.py

 def hello(txt):
     return "hello " + txt
 
 @GraalPyModuleBinding("hello")
 public interface Hello {
     String hello(String txt);
 }
 
 @Inject
 public void inject(Hello hello) {
     hello.hello("python");
 }
 
  • Required Element Summary

    Required Elements
    Modifier and Type
    Required Element
    Description
    Name of the Python module to import.
  • Element Details

    • value

      String value
      Name of the Python module to import. This may be a relative or absolute import. In general, a valid value is anything that can follow after the import keyword in Python.
      Returns:
      name of Python module