Context manager to yield a Dask client from the global singleton cluster. Args: config (DictConfig, optional): Cluster config. setup_fn (Callable[[], dict], optional): A setup function that runs on each worker and returns a dictionary of environment variables. Y
(
config: DictConfig = None, setup_fn: Optional[Callable[[], dict]] = None
)
| 299 | |
| 300 | @contextmanager |
| 301 | def get_client( |
| 302 | config: DictConfig = None, setup_fn: Optional[Callable[[], dict]] = None |
| 303 | ) -> Generator[Client, None, None]: |
| 304 | """Context manager to yield a Dask client from the global singleton cluster. |
| 305 | |
| 306 | Args: |
| 307 | config (DictConfig, optional): Cluster config. |
| 308 | setup_fn (Callable[[], dict], optional): A setup function that runs |
| 309 | on each worker and returns a dictionary of environment variables. |
| 310 | |
| 311 | Yields: |
| 312 | Client: A Dask client instance tied to the global cluster. |
| 313 | |
| 314 | Example: |
| 315 | >>> with get_client() as client: |
| 316 | ... results = client.map(lambda x: x**2, range(10)) |
| 317 | """ |
| 318 | client = build_client(config) |
| 319 | if setup_fn is not None: |
| 320 | plugin = DictReturnWorkerPlugin(setup_fn) |
| 321 | reg = getattr(client, "register_worker_plugin", None) |
| 322 | if reg is None: |
| 323 | raise RuntimeError( |
| 324 | "This Dask version lacks register_worker_plugin; please upgrade." |
| 325 | ) |
| 326 | reg(plugin, name="env") |
| 327 | try: |
| 328 | yield client |
| 329 | finally: |
| 330 | # Avoid shutdown for LocalCluster and LocalCUDACluster |
| 331 | cluster = getattr(client, "cluster", None) |
| 332 | |
| 333 | # always close the client first |
| 334 | client.close() |
| 335 | |
| 336 | if cluster is not None: |
| 337 | close = getattr(cluster, "close", None) |
| 338 | if callable(close): |
| 339 | close() |
| 340 | else: |
| 341 | shutdown = getattr(cluster, "shutdown", None) |
| 342 | if callable(shutdown): |
| 343 | shutdown() |
| 344 | |
| 345 | |
| 346 | @contextmanager |
searching dependent graphs…