Skip to content

Commit

Permalink
feat: add cdf invoke function to implicitly use conf and di from work…
Browse files Browse the repository at this point in the history
…space when active
  • Loading branch information
z3z1ma committed Aug 20, 2024
1 parent 0887aaf commit 7f965c5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/cdf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
)
from cdf.core.context import (
get_active_workspace,
invoke,
resolve,
set_active_workspace,
use_workspace,
Expand All @@ -31,5 +32,6 @@
"get_active_workspace",
"set_active_workspace",
"resolve",
"invoke",
"use_workspace",
]
13 changes: 13 additions & 0 deletions src/cdf/core/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@

import contextlib
import functools
import logging
import typing as t
from contextvars import ContextVar, Token

if t.TYPE_CHECKING:
from cdf.core.injector import Lifecycle
from cdf.core.workspace import Workspace

logger = logging.getLogger(__name__)

_ACTIVE_WORKSPACE: ContextVar[t.Optional["Workspace"]] = ContextVar(
"active_workspace", default=None
)
Expand Down Expand Up @@ -93,6 +96,16 @@ def wrapper(*args: t.Any, **kwargs: t.Any) -> T:
return _resolve


def invoke(func_or_cls: t.Callable, *args: t.Any, **kwargs: t.Any) -> t.Any:
"""Invoke a function or class with resolved dependencies."""
workspace = get_active_workspace()
if workspace is None:
logger.debug("Invoking %s without a bound workspace", func_or_cls)
return func_or_cls(*args, **kwargs)
logger.debug("Invoking %s bound to workspace %s", func_or_cls, workspace)
return workspace.invoke(func_or_cls, *args, **kwargs)


def get_default_callable_lifecycle() -> t.Optional["Lifecycle"]:
"""Get the default lifecycle for callables when otherwise unspecified."""
return _DEFAULT_CALLABLE_LIFECYCLE.get()
Expand Down

0 comments on commit 7f965c5

Please sign in to comment.