Wrap a user-defined function for a WorkerPlugin. This wrapper inspects the function's signature and automatically supplies keyword arguments from the worker's environment (`worker.plugins["env"]`) when they match parameter names of the function and are not explicitly provided by the
(func: Callable)
| 212 | |
| 213 | |
| 214 | def wrap_func_with_worker_env(func: Callable) -> Callable: |
| 215 | """Wrap a user-defined function for a WorkerPlugin. |
| 216 | |
| 217 | This wrapper inspects the function's signature and automatically |
| 218 | supplies keyword arguments from the worker's environment (`worker.plugins["env"]`) |
| 219 | when they match parameter names of the function and are not explicitly |
| 220 | provided by the caller. |
| 221 | |
| 222 | **Conflict detection**: |
| 223 | If both the worker environment and the call's `kwargs` provide the same |
| 224 | argument name, the wrapper raises a ``ValueError`` before calling the |
| 225 | underlying function. |
| 226 | |
| 227 | Args: |
| 228 | func (Callable): |
| 229 | The original user-defined function to be executed on the worker. |
| 230 | It may have positional parameters, keyword parameters, and/or |
| 231 | a ``**kwargs`` catch-all. |
| 232 | |
| 233 | Returns: |
| 234 | Callable: |
| 235 | A wrapped function that: |
| 236 | 1. Runs on the worker. |
| 237 | 2. Retrieves the environment dict from ``worker.plugins["env"]``. |
| 238 | 3. Detects and errors on conflicts with explicit keyword arguments. |
| 239 | 4. Supplies any missing keyword arguments from the environment. |
| 240 | |
| 241 | Raises: |
| 242 | ValueError: |
| 243 | If there is at least one parameter name that is present both in the |
| 244 | worker environment and in the keyword arguments provided to the call. |
| 245 | |
| 246 | Notes: |
| 247 | - Only environment keys that match the function's parameter names |
| 248 | (or any keys if the function accepts ``**kwargs``) will be considered |
| 249 | for injection. |
| 250 | |
| 251 | Example: |
| 252 | >>> def setup_fn(): |
| 253 | ... return {"bias": 7} |
| 254 | ... |
| 255 | >>> def add_bias(x, bias): |
| 256 | ... return x + bias |
| 257 | ... |
| 258 | >>> with get_client(local_config, setup_fn=setup_fn) as client: |
| 259 | ... # 'bias' comes from worker env, no need to pass it explicitly |
| 260 | ... futs = client.map(add_bias, [1, 2]) |
| 261 | ... print(client.gather(futs)) |
| 262 | [8, 9] |
| 263 | |
| 264 | >>> # Passing conflicting 'bias' both in env and kwargs will error: |
| 265 | >>> with pytest.raises(ValueError): |
| 266 | ... client.map(add_bias, [1, 2], bias=5) |
| 267 | """ |
| 268 | sig = inspect.signature(func) |
| 269 | param_names = set(sig.parameters.keys()) |
| 270 | accepts_var_kw = any( |
| 271 | p.kind is inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values() |
no test coverage detected
searching dependent graphs…