withContext<T> method

T withContext<T>(
  1. T action(
    1. PyObject
    )
)

Runs a synchronous Python context manager in a temporary resource scope.

To return a locally created resource beyond this boundary, use its PyObject.detachToParentScope method before returning it.

Implementation

T withContext<T>(T Function(PyObject) action) => ResourceScope.scope(() {
  final enter = getAttr('__enter__');
  final value = enter.call0();
  try {
    return action(value);
  } finally {
    final exit = getAttr('__exit__');
    exit.callN([.getConst(.none), .getConst(.none), .getConst(.none)]);
  }
});