Class PythonContextRuntime

java.lang.Object
io.micronaut.context.python.PythonContextRuntime

public final class PythonContextRuntime extends Object
Runtime coordination point for generated Python bridge classes.

This type is the static entry point of generated bridge classes: it resolves the application runtime installed by GraalPyContextFactory (see PythonApplicationRuntime), resolves classes and scripts from the primary context or a PythonPool, mirrors host members into event-loop contexts and executes the shared Python helper functions. Execution tracking and the per-context state live in PythonContextRegistry.

Since:
5.2.0
Author:
Micronaut Team
  • Field Details

  • Method Details

    • getContext

      public static org.graalvm.polyglot.Context getContext()
      The primary context of the installed application runtime.
      Returns:
      The primary context
      Throws:
      IllegalStateException - When no application runtime is installed
    • isInitialized

      public static boolean isInitialized()
      Check if an application runtime is installed.
      Returns:
      true if the primary context is available, false otherwise
    • isLiveInstance

      public static boolean isLiveInstance(@Nullable org.graalvm.polyglot.Value value)
      Whether a Python object owned by a generated stub belongs to the primary context of a running application.

      A stub that owns its Python object (one created through a constructor of the stub rather than wrapping an existing object) creates it on first use and again when the application the object was created in has shut down, that is when its runtime is no longer installed: a stub held in a JVM-wide singleton, such as a service loaded once per JVM, then follows the application currently running instead of failing with a cancelled execution of a closed context. An object of an enclosing application stays live while a nested ApplicationContext.run(...) is the current one, so the beans of the enclosing application keep their state across the nested run.

      Parameters:
      value - The Python object the stub holds, or null when none was created yet
      Returns:
      true when the object belongs to the primary context of an installed runtime
      Since:
      5.2.0
    • isCurrentContext

      public static boolean isCurrentContext(@Nullable org.graalvm.polyglot.Context context)
      Check whether the supplied context is the primary context of the installed runtime, the one a generated wrapper creates its Python object in.

      Context.equals(Object) compares the underlying context, so the creator instance and the view returned by Value.getContext() both match the primary context.

      Parameters:
      context - The context to compare
      Returns:
      true when the context is the primary runtime context
      Since:
      5.2.0
    • resetContext

      public static void resetContext()
      Uninstall every installed application runtime, so no application is running as far as generated code is concerned; with context reuse enabled it only reloads the Python modules of the primary context. An application shutting down uninstalls its own runtime through GraalPyContextFactory; this method serves tests and tooling that reset the JVM-wide state between applications.
    • setReuseContext

      public static void setReuseContext(boolean reuse)
      If context reuse is set to true, then the context will never be cleared.
      Parameters:
      reuse - tells if the context should be reused
    • isReuseContext

      public static boolean isReuseContext()
      Returns true if the context should be reused.
      Returns:
      the reuse flag
    • asyncInstance

      @Deprecated(since="5.2.14", forRemoval=true) public static org.graalvm.polyglot.Value asyncInstance(org.graalvm.polyglot.Value fallback, PythonContextRuntime.PythonClassReference classReference)
      Deprecated, for removal: This API element is subject to removal in a future version.
      The bean's own object is always used; generated code no longer needs to resolve it
      Resolve the Python instance an async method of a generated wrapper runs on.

      A Python bean that is not @ContextPooled -- a singleton, a prototype instance, a factory product -- is one Python object in the context that created it, and its coroutines run there, on the asyncio loop that context has for the calling event loop. Running them on a copy in the event-loop context instead would give every event loop its own object: state the application keeps in a singleton would no longer be shared, and a copy cannot be constructed faithfully anyway, as it would need every constructor argument again. Pooled beans and route modules are resolved per context by the pool, event-loop contexts included.

      Parameters:
      fallback - The bean's Python object
      classReference - The Python class reference
      Returns:
      The bean's Python object
      Since:
      5.2.0
    • rememberAsyncMember

      @Deprecated(since="5.2.14", forRemoval=true) public static void rememberAsyncMember(org.graalvm.polyglot.Value source, String name, @Nullable Object value)
      Deprecated, for removal: This API element is subject to removal in a future version.
      Python beans are no longer copied into event-loop contexts
      Formerly remembered a host-side member assigned to a Python object so event-loop copies of the object could mirror it. Python beans are no longer copied into event-loop contexts, so there is nothing to remember.
      Parameters:
      source - The Python object
      name - The member name
      value - The host value
    • findPooledClass

      public static org.graalvm.polyglot.Value findPooledClass(PythonContextRuntime.PythonClassReference classReference)
      Obtain a pooled Python class instance (per-context cached).
      Parameters:
      classReference - The Python class reference
      Returns:
      The pooled class instance (Value) from some context
      Since:
      5.2.0
    • findPooledClass

      public static org.graalvm.polyglot.Value findPooledClass(PythonContextRuntime.PythonClassReference classReference, org.graalvm.polyglot.Context context)
      Obtain a pooled Python class instance from a specific context.
      Parameters:
      classReference - The Python class reference
      context - The context
      Returns:
      The pooled class instance (Value)
      Since:
      5.2.0
    • withPooled

      public static <T> T withPooled(PythonContextRuntime.PythonClassReference classReference, Function<org.graalvm.polyglot.Value, T> fn)
      Execute a function with a borrowed pooled class instance.
      Type Parameters:
      T - Result type returned by the function
      Parameters:
      classReference - The Python class reference
      fn - Function receiving the pooled Value
      Returns:
      Result returned from the function
      Since:
      5.2.0
    • findPooledScript

      public static org.graalvm.polyglot.Value findPooledScript(String packageName, String scriptName)
      Obtain a pooled Python script/module object.
      Parameters:
      packageName - The Python package
      scriptName - The script/module name
      Returns:
      A pooled script Value
    • findPooledScript

      public static org.graalvm.polyglot.Value findPooledScript(String packageName, String scriptName, org.graalvm.polyglot.Context context)
      Obtain a pooled Python script/module object from a specific context.
      Parameters:
      packageName - The Python package
      scriptName - The script/module name
      context - The context
      Returns:
      A pooled script Value
    • withPooledScript

      public static <T> T withPooledScript(String packageName, String scriptName, Function<org.graalvm.polyglot.Value, T> fn)
      Execute a function with a borrowed pooled script/module object.
      Type Parameters:
      T - Result type returned by the function
      Parameters:
      packageName - The package
      scriptName - The script name
      fn - Function receiving the script Value
      Returns:
      Result returned from the function
    • withPooledValue

      public static PooledValue withPooledValue(String expression)
      Create a wrapper for a Python value that is evaluated and cached in each pooled context.
      Parameters:
      expression - The Python expression or statements to evaluate
      Returns:
      A pooled value wrapper
      Since:
      5.2.0
    • withPooledValue

      public static <T> T withPooledValue(String expression, Function<org.graalvm.polyglot.Value, T> fn)
      Execute a callback with a Python value evaluated and cached in a borrowed pooled context.
      Type Parameters:
      T - Result type returned by the function
      Parameters:
      expression - The Python expression or statements to evaluate
      fn - Function receiving the pooled value
      Returns:
      Result returned from the function
      Since:
      5.2.0
    • injectPooledScript

      public static void injectPooledScript(String packageName, String scriptName, String attribute, Object value)
      Inject an attribute into all pooled script contexts.
      Parameters:
      packageName - The package
      scriptName - The script name
      attribute - The attribute name
      value - The value to inject
    • injectPooledScriptAsync

      public static void injectPooledScriptAsync(String packageName, String scriptName, String attribute, Object value)
      Inject an async-adapted attribute into all pooled script contexts.
      Parameters:
      packageName - The package
      scriptName - The script name
      attribute - The attribute name
      value - The value to inject
    • invokePooled

      public static org.graalvm.polyglot.Value invokePooled(PythonContextRuntime.PythonClassReference classReference, String methodName, Object... args)
      Invoke a method on a pooled class instance.
      Parameters:
      classReference - The Python class reference
      methodName - The method name
      args - Arguments
      Returns:
      The polyglot result
      Since:
      5.2.0
    • invokePooledAsync

      public static CompletionStage<?> invokePooledAsync(PythonContextRuntime.PythonClassReference classReference, String methodName, Object... args)
      Invoke an async method on a pooled class instance and drive the coroutine while the borrowed context is still leased to the call; the context is returned to the pool once the stage completes.
      Parameters:
      classReference - The Python class reference
      methodName - The method name
      args - Arguments
      Returns:
      The stage of the coroutine
      Since:
      5.2.0
    • invokePooledScriptAsync

      public static CompletionStage<?> invokePooledScriptAsync(String packageName, String scriptName, String methodName, Object... args)
      Invoke an async method on a pooled script and drive the coroutine while the borrowed context is still leased to the call; the context is returned to the pool once the stage completes.
      Parameters:
      packageName - The package
      scriptName - The script name
      methodName - The method name
      args - Arguments
      Returns:
      The stage of the coroutine
      Since:
      5.2.0
    • invokePooledPublisher

      public static Publisher<?> invokePooledPublisher(PythonContextRuntime.PythonClassReference classReference, String methodName, Object... args)
      Invoke an async generator method on a pooled class instance and expose the generator as a publisher. On a Netty event loop the generator runs in the loop's own context, which needs no lease; without a loop the call fails, since nothing could drive the generator after the borrowed context is returned to the pool.
      Parameters:
      classReference - The Python class reference
      methodName - The method name
      args - Arguments
      Returns:
      The publisher of the generator's elements
      Since:
      5.2.3
    • invokePooledScriptPublisher

      public static Publisher<?> invokePooledScriptPublisher(String packageName, String scriptName, String methodName, Object... args)
      Invoke an async generator function of a pooled script and expose the generator as a publisher; see invokePooledPublisher(PythonClassReference, String, Object...).
      Parameters:
      packageName - The package
      scriptName - The script name
      methodName - The function name
      args - Arguments
      Returns:
      The publisher of the generator's elements
      Since:
      5.2.3
    • invokePooledScript

      public static org.graalvm.polyglot.Value invokePooledScript(String packageName, String scriptName, String methodName, Object... args)
      Invoke a method on a pooled script instance.
      Parameters:
      packageName - The package
      scriptName - The script name
      methodName - The method name
      args - Arguments
      Returns:
      The polyglot result
    • newIntroduction

      public static org.graalvm.polyglot.Value newIntroduction(PythonContextRuntime.PythonClassReference classReference, Object... args)
      Create an instance that is abstract and fill out the abstract methods with stubs to be later populated.
      Parameters:
      classReference - The Python class reference
      args - The args
      Returns:
      The new instance
      Since:
      5.2.0
    • newIntroduction

      public static org.graalvm.polyglot.Value newIntroduction(org.graalvm.polyglot.Context context, PythonContextRuntime.PythonClassReference classReference, Object... args)
      Create an abstract introduction instance in a supplied context.
      Parameters:
      context - The target context
      classReference - The Python class reference
      args - The args
      Returns:
      The new instance
      Since:
      5.2.0
    • newIntroductionWithDefaultedTrailingNulls

      public static org.graalvm.polyglot.Value newIntroductionWithDefaultedTrailingNulls(PythonContextRuntime.PythonClassReference classReference, int requiredArgCount, Object... args)
      Create a new abstract introduction instance, omitting trailing null arguments that correspond to Python constructor defaults.
      Parameters:
      classReference - The Python class reference
      requiredArgCount - The number of non-defaulted positional constructor arguments
      args - The arguments
      Returns:
      The new instance
      Since:
      5.2.0
    • newIntroductionWithDefaultedTrailingNulls

      public static org.graalvm.polyglot.Value newIntroductionWithDefaultedTrailingNulls(org.graalvm.polyglot.Context context, PythonContextRuntime.PythonClassReference classReference, int requiredArgCount, Object... args)
      Create an abstract introduction instance in a supplied context, omitting trailing defaults.
      Parameters:
      context - The target context
      classReference - The Python class reference
      requiredArgCount - The number of non-defaulted positional constructor arguments
      args - The arguments
      Returns:
      The new instance
      Since:
      5.2.0
    • newInstance

      public static org.graalvm.polyglot.Value newInstance(PythonContextRuntime.PythonClassReference classReference, Object... args)
      Create a new instance for the given class reference and args.
      Parameters:
      classReference - The Python class reference
      args - The args
      Returns:
      The new instance
      Since:
      5.2.0
    • newInstance

      public static org.graalvm.polyglot.Value newInstance(org.graalvm.polyglot.Context context, PythonContextRuntime.PythonClassReference classReference, Object... args)
      Create a new instance in a supplied context.
      Parameters:
      context - The target context
      classReference - The Python class reference
      args - The args
      Returns:
      The new instance
      Since:
      5.2.0
    • enumValue

      public static org.graalvm.polyglot.Value enumValue(PythonContextRuntime.PythonClassReference classReference, String name)
      Resolve a Python enum constant by its Java enum name.
      Parameters:
      classReference - The Python class reference
      name - The enum constant name
      Returns:
      The Python enum constant
      Since:
      5.2.0
    • enumValue

      public static org.graalvm.polyglot.Value enumValue(org.graalvm.polyglot.Context context, PythonContextRuntime.PythonClassReference classReference, String name)
      Resolve a Python enum constant by its Java enum name in a supplied context.
      Parameters:
      context - The target context
      classReference - The Python class reference
      name - The enum constant name
      Returns:
      The Python enum constant
      Since:
      5.2.0
    • newInstanceWithDefaultedTrailingNulls

      public static org.graalvm.polyglot.Value newInstanceWithDefaultedTrailingNulls(PythonContextRuntime.PythonClassReference classReference, int requiredArgCount, Object... args)
      Create a new instance, omitting trailing null arguments that correspond to Python constructor defaults.
      Parameters:
      classReference - The Python class reference
      requiredArgCount - The number of non-defaulted positional constructor arguments
      args - The arguments
      Returns:
      The new instance
      Since:
      5.2.0
    • newInstanceWithDefaultedTrailingNulls

      public static org.graalvm.polyglot.Value newInstanceWithDefaultedTrailingNulls(org.graalvm.polyglot.Context context, PythonContextRuntime.PythonClassReference classReference, int requiredArgCount, Object... args)
      Create a new instance in a supplied context, omitting trailing defaults.
      Parameters:
      context - The target context
      classReference - The Python class reference
      requiredArgCount - The number of non-defaulted positional constructor arguments
      args - The arguments
      Returns:
      The new instance
      Since:
      5.2.0
    • newUninitializedInstance

      public static org.graalvm.polyglot.Value newUninitializedInstance(PythonContextRuntime.PythonClassReference classReference)
      Create a Python instance without invoking __init__.
      Parameters:
      classReference - The Python class reference
      Returns:
      The new uninitialized instance
      Since:
      5.2.0
    • newUninitializedInstance

      public static org.graalvm.polyglot.Value newUninitializedInstance(org.graalvm.polyglot.Context context, PythonContextRuntime.PythonClassReference classReference)
      Create an instance without invoking __init__ in a supplied context.
      Parameters:
      context - The target context
      classReference - The Python class reference
      Returns:
      The new uninitialized instance
      Since:
      5.2.0
    • newUninitializedInstance

      public static org.graalvm.polyglot.Value newUninitializedInstance(org.graalvm.polyglot.Context context, PythonContextRuntime.PythonClassReference classReference, @Nullable Map<String,Object> props)
      Create an instance without invoking __init__ and populate its properties in a supplied context.
      Parameters:
      context - The target context
      classReference - The Python class reference
      props - Map of property names to values
      Returns:
      The populated uninitialized instance
      Since:
      5.2.0
    • allocateInstance

      public static PythonContextRuntime.AllocatedInstance allocateInstance(PythonContextRuntime.PythonClassReference classReference, Object... args)
      Allocate an instance of a class as newInstance(PythonClassReference, Object...) would, through the __new__ of the class with the constructor arguments, without running __init__, which initializeInstance(AllocatedInstance) runs next with the same arguments. A Python class extending a Java class whose super constructor takes no argument is created this way: the generated Java instance is constructed and bound to the Python object in between, so that the inherited Java methods __init__ calls run on it. A class whose metaclass customizes __call__ is created by calling it, as before.
      Parameters:
      classReference - The Python class reference
      args - The args
      Returns:
      The allocated instance
      Since:
      5.2.16
    • allocateInstanceWithDefaultedTrailingNulls

      public static PythonContextRuntime.AllocatedInstance allocateInstanceWithDefaultedTrailingNulls(PythonContextRuntime.PythonClassReference classReference, int requiredArgCount, Object... args)
      Allocate an instance of a class without __init__, omitting trailing null arguments that correspond to Python constructor defaults.
      Parameters:
      classReference - The Python class reference
      requiredArgCount - The number of non-defaulted positional constructor arguments
      args - The arguments
      Returns:
      The allocated instance
      Since:
      5.2.16
    • initializeInstance

      public static void initializeInstance(PythonContextRuntime.AllocatedInstance allocated)
      Run __init__ on an instance allocateInstance(PythonContextRuntime.PythonClassReference, Object...) returned, with the arguments __new__ received, as a call of the class would: only when the instance is one of the class and was not created by a customized metaclass __call__ already.
      Parameters:
      allocated - The allocated instance
      Since:
      5.2.16
    • newInstance

      public static org.graalvm.polyglot.Value newInstance(PythonContextRuntime.PythonClassReference classReference, @Nullable Map<String,Object> props)
      Create a new instance and set properties via member assignment when no constructor exists.
      Parameters:
      classReference - The Python class reference
      props - Map of property names to values
      Returns:
      The new instance with members populated
      Since:
      5.2.0
    • newInstance

      public static org.graalvm.polyglot.Value newInstance(org.graalvm.polyglot.Context context, PythonContextRuntime.PythonClassReference classReference, @Nullable Map<String,Object> props)
      Create a new instance and populate its properties in a supplied context.
      Parameters:
      context - The target context
      classReference - The Python class reference
      props - Map of property names to values
      Returns:
      The new instance with members populated
      Since:
      5.2.0
    • newFrozenDataclassInstance

      public static org.graalvm.polyglot.Value newFrozenDataclassInstance(PythonContextRuntime.PythonClassReference classReference, @Nullable Map<String,Object> props)
      Create a new frozen dataclass instance and set properties without invoking __init__.
      Parameters:
      classReference - The Python class reference
      props - Map of property names to values
      Returns:
      The new frozen dataclass instance with members populated
      Since:
      5.2.0
    • newFrozenDataclassInstance

      public static org.graalvm.polyglot.Value newFrozenDataclassInstance(org.graalvm.polyglot.Context context, PythonContextRuntime.PythonClassReference classReference, @Nullable Map<String,Object> props)
      Create a frozen dataclass instance and populate its properties in a supplied context.
      Parameters:
      context - The target context
      classReference - The Python class reference
      props - Map of property names to values
      Returns:
      The new instance with members populated
      Since:
      5.2.0
    • setInstanceProperty

      public static void setInstanceProperty(org.graalvm.polyglot.Value instance, String name, @Nullable Object value)
      Set a property on an instance without invoking an overridden __setattr__ implementation.
      Parameters:
      instance - The target instance
      name - The property name
      value - The property value
      Since:
      5.2.0
    • findClass

      public static org.graalvm.polyglot.Value findClass(PythonContextRuntime.PythonClassReference classReference)
      Find a Python class by pre-split class reference.
      Parameters:
      classReference - The Python class reference
      Returns:
      The class Value
      Since:
      5.2.0
    • findClass

      public static org.graalvm.polyglot.Value findClass(PythonContextRuntime.PythonClassReference classReference, org.graalvm.polyglot.Context ctx)
      The class in a given context, rather than in the current one.
      Parameters:
      classReference - The class
      ctx - The context to resolve it in
      Returns:
      The class Value, belonging to that context
      Since:
      5.2.10
    • findScript

      public static org.graalvm.polyglot.Value findScript(String packageName, String scriptName)
      Find a Python script/module Value.
      Parameters:
      packageName - The package name (or python for top-level)
      scriptName - The script/module name
      Returns:
      The module Value
    • invokeStaticMethod

      public static org.graalvm.polyglot.Value invokeStaticMethod(PythonContextRuntime.PythonClassReference classReference, String methodName, Object... args)
      Invoke a static method on the given Python class.
      Parameters:
      classReference - The Python class reference
      methodName - The method name
      args - The method arguments
      Returns:
      The method result
      Since:
      5.2.0
    • withExecutionFrame

      @Internal public static <T, X extends Throwable> T withExecutionFrame(org.graalvm.polyglot.Context context, ScopedValue.CallableOp<T,X> operation) throws X
      Run host-initiated Python code inside an execution frame of the context, so shutdown waits for it and nested bridge calls share the frame.
      Type Parameters:
      T - The result type
      X - The checked exception type the operation may throw
      Parameters:
      context - The context the operation executes in
      operation - The operation
      Returns:
      The operation result
      Throws:
      X - When the operation throws
    • tryWithExecutionFrame

      @Internal public static boolean tryWithExecutionFrame(org.graalvm.polyglot.Context context, Runnable operation)
      Run a callback inside an execution frame unless its context is closing or already closed, in which case the callback is skipped; the decision and the execution count are one step.
      Parameters:
      context - The context of the callback
      operation - The callback
      Returns:
      false when the callback was skipped
    • withTrackedExecutionFrame

      @Internal public static <T, X extends Throwable> T withTrackedExecutionFrame(org.graalvm.polyglot.Context context, ScopedValue.CallableOp<T,X> operation) throws X
      Run an operation inside an execution frame of a context that must still be tracked and not closing: unlike withExecutionFrame(Context, ScopedValue.CallableOp) this never creates the state of an unknown (closed) context. Used for callbacks on channels that outlive a Python context.
      Type Parameters:
      T - The result type
      X - The exception type
      Parameters:
      context - The context
      operation - The operation
      Returns:
      The result
      Throws:
      X - When the operation throws
      IllegalStateException - When the context is closing or closed
    • helper

      @Internal public static org.graalvm.polyglot.Value helper(org.graalvm.polyglot.Context context, String name)
      A function of the micronaut_runtime module, resolved once per context.

      Helpers are stored per context because Graal values cannot be shared across contexts. Their initialization deliberately takes no Java monitor, because GraalPy operations acquire the Python GIL: a thread that owns the GIL and re-enters the runtime from Python would deadlock with a thread holding the monitor while waiting for the GIL. Concurrent first calls are safe instead because the module import is serialised by the Python import lock and the caches are atomic.

      Parameters:
      context - The context
      name - The function name
      Returns:
      The function