Skip to content

API Reference

JSArray

Bases: MutableSequence[PythonJSConvertedTypes], JSObjectImpl

JavaScript array.

Has Pythonic MutableSequence methods (e.g., insert(), __getitem__(), ...).

Source code in src/py_mini_racer/_objects.py
class JSArray(MutableSequence[PythonJSConvertedTypes], JSObjectImpl):
    """JavaScript array.

    Has Pythonic MutableSequence methods (e.g., `insert()`, `__getitem__()`, ...).
    """

    def __len__(self) -> int:
        ret = self._ctx.get_object_item(self, "length")
        return cast(int, ret)

    def __getitem__(self, index: int | slice) -> Any:
        if not isinstance(index, int):
            raise TypeError

        index = op_index(index)
        if index < 0:
            index += len(self)

        if 0 <= index < len(self):
            return self._ctx.get_object_item(self, index)

        raise IndexError

    def __setitem__(self, index: int | slice, val: Any) -> None:
        if not isinstance(index, int):
            raise TypeError

        self._ctx.set_object_item(self, index, val)

    def __delitem__(self, index: int | slice) -> None:
        if not isinstance(index, int):
            raise TypeError

        if index >= len(self) or index < -len(self):
            # JavaScript Array.prototype.splice() just ignores deletion beyond the
            # end of the array, meaning if you pass a very large value here it would
            # do nothing. Likewise, it just caps negative values at the length of the
            # array, meaning if you pass a very negative value here it would just
            # delete element 0.
            # For consistency with Python lists, let's tell the caller they're out of
            # bounds:
            raise JSArrayIndexError

        return self._ctx.del_from_array(self, index)

    def insert(self, index: int, new_obj: PythonJSConvertedTypes) -> None:
        return self._ctx.array_insert(self, index, new_obj)

    def __iter__(self) -> Iterator[PythonJSConvertedTypes]:
        for i in range(len(self)):
            yield self[i]

JSArrayIndexError

Bases: IndexError, MiniRacerBaseException

Invalid index into a JSArray.

Source code in src/py_mini_racer/_objects.py
class JSArrayIndexError(IndexError, MiniRacerBaseException):
    """Invalid index into a JSArray."""

    def __init__(self) -> None:
        super().__init__("JSArray deletion out of range")

JSEvalException

Bases: MiniRacerBaseException

JavaScript could not be executed.

Source code in src/py_mini_racer/_types.py
class JSEvalException(MiniRacerBaseException):
    """JavaScript could not be executed."""

JSFunction

Bases: JSMappedObject

JavaScript function.

You can call this object from Python, passing in positional args to match what the JavaScript function expects, along with a keyword argument, timeout_sec.

Source code in src/py_mini_racer/_objects.py
class JSFunction(JSMappedObject):
    """JavaScript function.

    You can call this object from Python, passing in positional args to match what the
    JavaScript function expects, along with a keyword argument, `timeout_sec`.
    """

    def __call__(
        self,
        *args: PythonJSConvertedTypes,
        this: JSObjectImpl | JSUndefinedType = JSUndefined,
        timeout_sec: Numeric | None = None,
    ) -> PythonJSConvertedTypes:
        return self._ctx.call_function(self, *args, this=this, timeout_sec=timeout_sec)

JSKeyError

Bases: JSEvalException, KeyError

No such key found.

Source code in src/py_mini_racer/_value_handle.py
class JSKeyError(JSEvalException, KeyError):
    """No such key found."""

JSOOMException

Bases: JSEvalException

JavaScript execution ran out of memory.

Source code in src/py_mini_racer/_value_handle.py
class JSOOMException(JSEvalException):
    """JavaScript execution ran out of memory."""

JSParseException

Bases: JSEvalException

JavaScript could not be parsed.

Source code in src/py_mini_racer/_value_handle.py
class JSParseException(JSEvalException):
    """JavaScript could not be parsed."""

JSPromise

Bases: JSObjectImpl

JavaScript Promise.

To get a value, call promise.get() to block, or await promise from within an async coroutine. Either will raise a Python exception if the JavaScript Promise is rejected.

Source code in src/py_mini_racer/_objects.py
class JSPromise(JSObjectImpl):
    """JavaScript Promise.

    To get a value, call `promise.get()` to block, or `await promise` from within an
    `async` coroutine. Either will raise a Python exception if the JavaScript Promise
    is rejected.
    """

    def get(self, *, timeout: Numeric | None = None) -> PythonJSConvertedTypes:
        """Get the value, or raise an exception. This call blocks.

        Args:
            timeout: number of milliseconds after which the execution is interrupted.
                This is deprecated; use timeout_sec instead.
        """

        future = SyncFuture()

        def future_caller(value: Any) -> None:
            future.set_result(value)

        self._attach_callbacks_to_promise(future_caller)

        results = future.get(timeout=timeout)
        return self._unpack_promise_results(results)

    def __await__(self) -> Generator[Any, None, Any]:
        return self._do_await().__await__()

    async def _do_await(self) -> PythonJSConvertedTypes:
        future: Future[PythonJSConvertedTypes] = Future()
        loop = future.get_loop()

        def future_caller(value: Any) -> None:
            loop.call_soon_threadsafe(future.set_result, value)

        self._attach_callbacks_to_promise(future_caller)

        results = await future
        return self._unpack_promise_results(results)

    def _attach_callbacks_to_promise(
        self,
        future_caller: Callable[[Any], None],
    ) -> None:
        """Attach the given Python callbacks to a JS Promise."""

        exit_stack = ExitStack()

        def on_resolved_and_cleanup(
            value: PythonJSConvertedTypes | JSEvalException,
        ) -> None:
            exit_stack.__exit__(None, None, None)
            future_caller([False, cast(JSArray, value)])

        on_resolved_js_func = exit_stack.enter_context(
            self._ctx.js_callback(on_resolved_and_cleanup)
        )

        def on_rejected_and_cleanup(
            value: PythonJSConvertedTypes | JSEvalException,
        ) -> None:
            exit_stack.__exit__(None, None, None)
            future_caller([True, cast(JSArray, value)])

        on_rejected_js_func = exit_stack.enter_context(
            self._ctx.js_callback(on_rejected_and_cleanup)
        )

        self._ctx.promise_then(self, on_resolved_js_func, on_rejected_js_func)

    def _unpack_promise_results(self, results: Any) -> PythonJSConvertedTypes:
        is_rejected, argv = results
        result = cast(PythonJSConvertedTypes, cast(JSArray, argv)[0])
        if is_rejected:
            raise JSPromiseError(result)
        return result

get(*, timeout=None)

Get the value, or raise an exception. This call blocks.

Parameters:

Name Type Description Default
timeout Numeric | None

number of milliseconds after which the execution is interrupted. This is deprecated; use timeout_sec instead.

None
Source code in src/py_mini_racer/_objects.py
def get(self, *, timeout: Numeric | None = None) -> PythonJSConvertedTypes:
    """Get the value, or raise an exception. This call blocks.

    Args:
        timeout: number of milliseconds after which the execution is interrupted.
            This is deprecated; use timeout_sec instead.
    """

    future = SyncFuture()

    def future_caller(value: Any) -> None:
        future.set_result(value)

    self._attach_callbacks_to_promise(future_caller)

    results = future.get(timeout=timeout)
    return self._unpack_promise_results(results)

JSPromiseError

Bases: MiniRacerBaseException

JavaScript rejected a promise.

Source code in src/py_mini_racer/_objects.py
class JSPromiseError(MiniRacerBaseException):
    """JavaScript rejected a promise."""

    def __init__(self, reason: PythonJSConvertedTypes) -> None:
        super().__init__(
            f"JavaScript rejected promise with reason: {_get_exception_msg(reason)}\n"
        )
        self.reason = reason

JSSymbol

Bases: JSMappedObject

JavaScript symbol.

Source code in src/py_mini_racer/_objects.py
class JSSymbol(JSMappedObject):
    """JavaScript symbol."""

JSTimeoutException

Bases: JSEvalException

JavaScript execution timed out.

Source code in src/py_mini_racer/_types.py
class JSTimeoutException(JSEvalException):
    """JavaScript execution timed out."""

    def __init__(self) -> None:
        super().__init__("JavaScript was terminated by timeout")

JSUndefinedType

The JavaScript undefined type.

Where JavaScript null is represented as None, undefined is represented as this type.

Source code in src/py_mini_racer/_types.py
class JSUndefinedType:
    """The JavaScript undefined type.

    Where JavaScript null is represented as None, undefined is represented as this
    type."""

    def __bool__(self) -> bool:
        return False

    def __repr__(self) -> str:
        return "JSUndefined"

JSValueError

Bases: JSEvalException, ValueError

Bad value passed to JavaScript engine.

Source code in src/py_mini_racer/_value_handle.py
class JSValueError(JSEvalException, ValueError):
    """Bad value passed to JavaScript engine."""

LibAlreadyInitializedError

Bases: MiniRacerBaseException

MiniRacer-wrapped V8 build not found.

Source code in src/py_mini_racer/_dll.py
class LibAlreadyInitializedError(MiniRacerBaseException):
    """MiniRacer-wrapped V8 build not found."""

    def __init__(self) -> None:
        super().__init__(
            "MiniRacer was already initialized before the call to init_mini_racer"
        )

LibNotFoundError

Bases: MiniRacerBaseException

MiniRacer-wrapped V8 build not found.

Source code in src/py_mini_racer/_dll.py
class LibNotFoundError(MiniRacerBaseException):
    """MiniRacer-wrapped V8 build not found."""

    def __init__(self, path: str):
        super().__init__(f"Native library or dependency not available at {path}")

MiniRacer

MiniRacer evaluates JavaScript code using a V8 isolate.

A MiniRacer instance can be explicitly closed using the close() method, or by using the MiniRacer as a context manager, i.e,:

with MiniRacer() as mr: ...

The MiniRacer instance will otherwise clean up the underlying V8 resource upon garbage collection.

Attributes:

Name Type Description
json_impl Any

JSON module used by helper methods default is json

Source code in src/py_mini_racer/_mini_racer.py
class MiniRacer:
    """
    MiniRacer evaluates JavaScript code using a V8 isolate.

    A MiniRacer instance can be explicitly closed using the close() method, or by using
    the MiniRacer as a context manager, i.e,:

    with MiniRacer() as mr:
        ...

    The MiniRacer instance will otherwise clean up the underlying V8 resource upon
    garbage collection.

    Attributes:
        json_impl: JSON module used by helper methods default is
            [json](https://docs.python.org/3/library/json.html)
    """

    json_impl: ClassVar[Any] = json

    def __init__(self) -> None:
        dll = init_mini_racer(ignore_duplicate_init=True)

        self._ctx = Context(dll)

        self.eval(INSTALL_SET_TIMEOUT)

    def close(self) -> None:
        """Close this MiniRacer instance.

        It is an error to use this MiniRacer instance or any JS objects returned by it
        after calling this method.
        """
        self._ctx.close()

    def __enter__(self) -> Self:
        return self

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        del exc_type
        del exc_val
        del exc_tb
        self.close()

    @property
    def v8_version(self) -> str:
        """Return the V8 version string."""
        return self._ctx.v8_version()

    def eval(
        self,
        code: str,
        timeout: Numeric | None = None,
        timeout_sec: Numeric | None = None,
        max_memory: int | None = None,
    ) -> PythonJSConvertedTypes:
        """Evaluate JavaScript code in the V8 isolate.

        Side effects from the JavaScript evaluation is persisted inside a context
        (meaning variables set are kept for the next evaluation).

        The JavaScript value returned by the last expression in `code` is converted to
        a Python value and returned by this method. Only primitive types are supported
        (numbers, strings, buffers...). Use the
        [py_mini_racer.MiniRacer.execute][] method to return more complex
        types such as arrays or objects.

        The evaluation can be interrupted by an exception for several reasons: a limit
        was reached, the code could not be parsed, a returned value could not be
        converted to a Python value.

        Args:
            code: JavaScript code
            timeout: number of milliseconds after which the execution is interrupted.
                This is deprecated; use timeout_sec instead.
            timeout_sec: number of seconds after which the execution is interrupted
            max_memory: hard memory limit, in bytes, after which the execution is
                interrupted.
        """

        if max_memory is not None:
            self.set_hard_memory_limit(max_memory)

        if timeout:
            # PyMiniRacer unfortunately uses milliseconds while Python and
            # Système international d'unités use seconds.
            timeout_sec = timeout / 1000

        return self._ctx.evaluate(code=code, timeout_sec=timeout_sec)

    def execute(
        self,
        expr: str,
        timeout: Numeric | None = None,
        timeout_sec: Numeric | None = None,
        max_memory: int | None = None,
    ) -> Any:
        """Helper to evaluate a JavaScript expression and return composite types.

        Returned value is serialized to JSON inside the V8 isolate and deserialized
        using `json_impl`.

        Args:
            expr: JavaScript expression
            timeout: number of milliseconds after which the execution is interrupted.
                This is deprecated; use timeout_sec instead.
            timeout_sec: number of seconds after which the execution is interrupted
            max_memory: hard memory limit, in bytes, after which the execution is
                interrupted.
        """

        if timeout:
            # PyMiniRacer unfortunately uses milliseconds while Python and
            # Système international d'unités use seconds.
            timeout_sec = timeout / 1000

        wrapped_expr = f"JSON.stringify((function(){{return ({expr})}})())"
        ret = self.eval(wrapped_expr, timeout_sec=timeout_sec, max_memory=max_memory)
        if not isinstance(ret, str):
            raise WrongReturnTypeException(type(ret))
        return self.json_impl.loads(ret)

    def call(
        self,
        expr: str,
        *args: Any,
        encoder: JSONEncoder | None = None,
        timeout: Numeric | None = None,
        timeout_sec: Numeric | None = None,
        max_memory: int | None = None,
    ) -> Any:
        """Helper to call a JavaScript function and return compositve types.

        The `expr` argument refers to a JavaScript function in the current V8
        isolate context. Further positional arguments are serialized using the JSON
        implementation `json_impl` and passed to the JavaScript function as arguments.

        Returned value is serialized to JSON inside the V8 isolate and deserialized
        using `json_impl`.

        Args:
            expr: JavaScript expression referring to a function
            encoder: Custom JSON encoder
            timeout: number of milliseconds after which the execution is
                interrupted.
            timeout_sec: number of seconds after which the execution is interrupted
            max_memory: hard memory limit, in bytes, after which the execution is
                interrupted
        """

        if timeout:
            # PyMiniRacer unfortunately uses milliseconds while Python and
            # Système international d'unités use seconds.
            timeout_sec = timeout / 1000

        json_args = self.json_impl.dumps(args, separators=(",", ":"), cls=encoder)
        js = f"{expr}.apply(this, {json_args})"
        return self.execute(js, timeout_sec=timeout_sec, max_memory=max_memory)

    def wrap_py_function(
        self,
        func: PyJsFunctionType,
    ) -> AbstractAsyncContextManager[JSFunction]:
        """Wrap a Python function such that it can be called from JS.

        To be wrapped and exposed in JavaScript, a Python function should:

          1. Be async,
          2. Accept variable positional arguments each of type PythonJSConvertedTypes,
             and
          3. Return one value of type PythonJSConvertedTypes (a type union which
             includes None).

        The function is rendered on the JavaScript side as an async function (i.e., a
        function which returns a Promise).

        Returns:
            An async context manager which, when entered, yields a JS Function which
            can be passed into MiniRacer and called by JS code.
        """

        return self._ctx.wrap_py_function(func)

    def set_hard_memory_limit(self, limit: int) -> None:
        """Set a hard memory limit on this V8 isolate.

        JavaScript execution will be terminated when this limit is reached.

        :param int limit: memory limit in bytes or 0 to reset the limit
        """
        self._ctx.set_hard_memory_limit(limit)

    def set_soft_memory_limit(self, limit: int) -> None:
        """Set a soft memory limit on this V8 isolate.

        The Garbage Collection will use a more aggressive strategy when
        the soft limit is reached but the execution will not be stopped.

        :param int limit: memory limit in bytes or 0 to reset the limit
        """
        self._ctx.set_soft_memory_limit(limit)

    def was_hard_memory_limit_reached(self) -> bool:
        """Return true if the hard memory limit was reached on the V8 isolate."""
        return self._ctx.was_hard_memory_limit_reached()

    def was_soft_memory_limit_reached(self) -> bool:
        """Return true if the soft memory limit was reached on the V8 isolate."""
        return self._ctx.was_soft_memory_limit_reached()

    def low_memory_notification(self) -> None:
        """Ask the V8 isolate to collect memory more aggressively."""
        self._ctx.low_memory_notification()

    def heap_stats(self) -> Any:
        """Return the V8 isolate heap statistics."""

        return self.json_impl.loads(self._ctx.heap_stats())

v8_version: str property

Return the V8 version string.

call(expr, *args, encoder=None, timeout=None, timeout_sec=None, max_memory=None)

Helper to call a JavaScript function and return compositve types.

The expr argument refers to a JavaScript function in the current V8 isolate context. Further positional arguments are serialized using the JSON implementation json_impl and passed to the JavaScript function as arguments.

Returned value is serialized to JSON inside the V8 isolate and deserialized using json_impl.

Parameters:

Name Type Description Default
expr str

JavaScript expression referring to a function

required
encoder JSONEncoder | None

Custom JSON encoder

None
timeout Numeric | None

number of milliseconds after which the execution is interrupted.

None
timeout_sec Numeric | None

number of seconds after which the execution is interrupted

None
max_memory int | None

hard memory limit, in bytes, after which the execution is interrupted

None
Source code in src/py_mini_racer/_mini_racer.py
def call(
    self,
    expr: str,
    *args: Any,
    encoder: JSONEncoder | None = None,
    timeout: Numeric | None = None,
    timeout_sec: Numeric | None = None,
    max_memory: int | None = None,
) -> Any:
    """Helper to call a JavaScript function and return compositve types.

    The `expr` argument refers to a JavaScript function in the current V8
    isolate context. Further positional arguments are serialized using the JSON
    implementation `json_impl` and passed to the JavaScript function as arguments.

    Returned value is serialized to JSON inside the V8 isolate and deserialized
    using `json_impl`.

    Args:
        expr: JavaScript expression referring to a function
        encoder: Custom JSON encoder
        timeout: number of milliseconds after which the execution is
            interrupted.
        timeout_sec: number of seconds after which the execution is interrupted
        max_memory: hard memory limit, in bytes, after which the execution is
            interrupted
    """

    if timeout:
        # PyMiniRacer unfortunately uses milliseconds while Python and
        # Système international d'unités use seconds.
        timeout_sec = timeout / 1000

    json_args = self.json_impl.dumps(args, separators=(",", ":"), cls=encoder)
    js = f"{expr}.apply(this, {json_args})"
    return self.execute(js, timeout_sec=timeout_sec, max_memory=max_memory)

close()

Close this MiniRacer instance.

It is an error to use this MiniRacer instance or any JS objects returned by it after calling this method.

Source code in src/py_mini_racer/_mini_racer.py
def close(self) -> None:
    """Close this MiniRacer instance.

    It is an error to use this MiniRacer instance or any JS objects returned by it
    after calling this method.
    """
    self._ctx.close()

eval(code, timeout=None, timeout_sec=None, max_memory=None)

Evaluate JavaScript code in the V8 isolate.

Side effects from the JavaScript evaluation is persisted inside a context (meaning variables set are kept for the next evaluation).

The JavaScript value returned by the last expression in code is converted to a Python value and returned by this method. Only primitive types are supported (numbers, strings, buffers...). Use the py_mini_racer.MiniRacer.execute method to return more complex types such as arrays or objects.

The evaluation can be interrupted by an exception for several reasons: a limit was reached, the code could not be parsed, a returned value could not be converted to a Python value.

Parameters:

Name Type Description Default
code str

JavaScript code

required
timeout Numeric | None

number of milliseconds after which the execution is interrupted. This is deprecated; use timeout_sec instead.

None
timeout_sec Numeric | None

number of seconds after which the execution is interrupted

None
max_memory int | None

hard memory limit, in bytes, after which the execution is interrupted.

None
Source code in src/py_mini_racer/_mini_racer.py
def eval(
    self,
    code: str,
    timeout: Numeric | None = None,
    timeout_sec: Numeric | None = None,
    max_memory: int | None = None,
) -> PythonJSConvertedTypes:
    """Evaluate JavaScript code in the V8 isolate.

    Side effects from the JavaScript evaluation is persisted inside a context
    (meaning variables set are kept for the next evaluation).

    The JavaScript value returned by the last expression in `code` is converted to
    a Python value and returned by this method. Only primitive types are supported
    (numbers, strings, buffers...). Use the
    [py_mini_racer.MiniRacer.execute][] method to return more complex
    types such as arrays or objects.

    The evaluation can be interrupted by an exception for several reasons: a limit
    was reached, the code could not be parsed, a returned value could not be
    converted to a Python value.

    Args:
        code: JavaScript code
        timeout: number of milliseconds after which the execution is interrupted.
            This is deprecated; use timeout_sec instead.
        timeout_sec: number of seconds after which the execution is interrupted
        max_memory: hard memory limit, in bytes, after which the execution is
            interrupted.
    """

    if max_memory is not None:
        self.set_hard_memory_limit(max_memory)

    if timeout:
        # PyMiniRacer unfortunately uses milliseconds while Python and
        # Système international d'unités use seconds.
        timeout_sec = timeout / 1000

    return self._ctx.evaluate(code=code, timeout_sec=timeout_sec)

execute(expr, timeout=None, timeout_sec=None, max_memory=None)

Helper to evaluate a JavaScript expression and return composite types.

Returned value is serialized to JSON inside the V8 isolate and deserialized using json_impl.

Parameters:

Name Type Description Default
expr str

JavaScript expression

required
timeout Numeric | None

number of milliseconds after which the execution is interrupted. This is deprecated; use timeout_sec instead.

None
timeout_sec Numeric | None

number of seconds after which the execution is interrupted

None
max_memory int | None

hard memory limit, in bytes, after which the execution is interrupted.

None
Source code in src/py_mini_racer/_mini_racer.py
def execute(
    self,
    expr: str,
    timeout: Numeric | None = None,
    timeout_sec: Numeric | None = None,
    max_memory: int | None = None,
) -> Any:
    """Helper to evaluate a JavaScript expression and return composite types.

    Returned value is serialized to JSON inside the V8 isolate and deserialized
    using `json_impl`.

    Args:
        expr: JavaScript expression
        timeout: number of milliseconds after which the execution is interrupted.
            This is deprecated; use timeout_sec instead.
        timeout_sec: number of seconds after which the execution is interrupted
        max_memory: hard memory limit, in bytes, after which the execution is
            interrupted.
    """

    if timeout:
        # PyMiniRacer unfortunately uses milliseconds while Python and
        # Système international d'unités use seconds.
        timeout_sec = timeout / 1000

    wrapped_expr = f"JSON.stringify((function(){{return ({expr})}})())"
    ret = self.eval(wrapped_expr, timeout_sec=timeout_sec, max_memory=max_memory)
    if not isinstance(ret, str):
        raise WrongReturnTypeException(type(ret))
    return self.json_impl.loads(ret)

heap_stats()

Return the V8 isolate heap statistics.

Source code in src/py_mini_racer/_mini_racer.py
def heap_stats(self) -> Any:
    """Return the V8 isolate heap statistics."""

    return self.json_impl.loads(self._ctx.heap_stats())

low_memory_notification()

Ask the V8 isolate to collect memory more aggressively.

Source code in src/py_mini_racer/_mini_racer.py
def low_memory_notification(self) -> None:
    """Ask the V8 isolate to collect memory more aggressively."""
    self._ctx.low_memory_notification()

set_hard_memory_limit(limit)

Set a hard memory limit on this V8 isolate.

JavaScript execution will be terminated when this limit is reached.

:param int limit: memory limit in bytes or 0 to reset the limit

Source code in src/py_mini_racer/_mini_racer.py
def set_hard_memory_limit(self, limit: int) -> None:
    """Set a hard memory limit on this V8 isolate.

    JavaScript execution will be terminated when this limit is reached.

    :param int limit: memory limit in bytes or 0 to reset the limit
    """
    self._ctx.set_hard_memory_limit(limit)

set_soft_memory_limit(limit)

Set a soft memory limit on this V8 isolate.

The Garbage Collection will use a more aggressive strategy when the soft limit is reached but the execution will not be stopped.

:param int limit: memory limit in bytes or 0 to reset the limit

Source code in src/py_mini_racer/_mini_racer.py
def set_soft_memory_limit(self, limit: int) -> None:
    """Set a soft memory limit on this V8 isolate.

    The Garbage Collection will use a more aggressive strategy when
    the soft limit is reached but the execution will not be stopped.

    :param int limit: memory limit in bytes or 0 to reset the limit
    """
    self._ctx.set_soft_memory_limit(limit)

was_hard_memory_limit_reached()

Return true if the hard memory limit was reached on the V8 isolate.

Source code in src/py_mini_racer/_mini_racer.py
def was_hard_memory_limit_reached(self) -> bool:
    """Return true if the hard memory limit was reached on the V8 isolate."""
    return self._ctx.was_hard_memory_limit_reached()

was_soft_memory_limit_reached()

Return true if the soft memory limit was reached on the V8 isolate.

Source code in src/py_mini_racer/_mini_racer.py
def was_soft_memory_limit_reached(self) -> bool:
    """Return true if the soft memory limit was reached on the V8 isolate."""
    return self._ctx.was_soft_memory_limit_reached()

wrap_py_function(func)

Wrap a Python function such that it can be called from JS.

To be wrapped and exposed in JavaScript, a Python function should:

  1. Be async,
  2. Accept variable positional arguments each of type PythonJSConvertedTypes, and
  3. Return one value of type PythonJSConvertedTypes (a type union which includes None).

The function is rendered on the JavaScript side as an async function (i.e., a function which returns a Promise).

Returns:

Type Description
AbstractAsyncContextManager[JSFunction]

An async context manager which, when entered, yields a JS Function which

AbstractAsyncContextManager[JSFunction]

can be passed into MiniRacer and called by JS code.

Source code in src/py_mini_racer/_mini_racer.py
def wrap_py_function(
    self,
    func: PyJsFunctionType,
) -> AbstractAsyncContextManager[JSFunction]:
    """Wrap a Python function such that it can be called from JS.

    To be wrapped and exposed in JavaScript, a Python function should:

      1. Be async,
      2. Accept variable positional arguments each of type PythonJSConvertedTypes,
         and
      3. Return one value of type PythonJSConvertedTypes (a type union which
         includes None).

    The function is rendered on the JavaScript side as an async function (i.e., a
    function which returns a Promise).

    Returns:
        An async context manager which, when entered, yields a JS Function which
        can be passed into MiniRacer and called by JS code.
    """

    return self._ctx.wrap_py_function(func)

init_mini_racer(*, flags=DEFAULT_V8_FLAGS, ignore_duplicate_init=False)

Initialize py_mini_racer (and V8).

This function can optionally be used to set V8 flags. This function can be called at most once, before any instances of MiniRacer are initialized. Instances of MiniRacer will automatically call this function to initialize MiniRacer and V8.

Source code in src/py_mini_racer/_dll.py
def init_mini_racer(
    *, flags: Iterable[str] = DEFAULT_V8_FLAGS, ignore_duplicate_init: bool = False
) -> ctypes.CDLL:
    """Initialize py_mini_racer (and V8).

    This function can optionally be used to set V8 flags. This function can be called
    at most once, before any instances of MiniRacer are initialized. Instances of
    MiniRacer will automatically call this function to initialize MiniRacer and V8.
    """

    global _dll_handle_context_manager  # noqa: PLW0603
    global _dll_handle  # noqa: PLW0603

    with _init_lock:
        if _dll_handle is None:
            _dll_handle_context_manager = _open_dll(flags)
            _dll_handle = _dll_handle_context_manager.__enter__()
            # Note: we never call _dll_handle_context_manager.__exit__() because it's
            # designed as a singleton. But we could if we wanted to!
        elif not ignore_duplicate_init:
            raise LibAlreadyInitializedError

        return _dll_handle