Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),

## [Unreleased]

## [1.5.3]

### Fixed

- `FnWithKwargs` call function fixed

## [1.5.2]

### Added
Expand Down
18 changes: 8 additions & 10 deletions kaizo/utils/fn.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,35 @@
from collections.abc import Callable
from copy import copy
from functools import partial
from typing import Generic, TypeVar

R = TypeVar("R")


class FnWithKwargs(Generic[R]):
fn: Callable[..., R]
args: tuple | None
kwargs: dict[str] | None
args: tuple
kwargs: dict[str]

def __init__(
self,
fn: Callable[..., R],
args: tuple | None = None,
kwargs: dict[str] | None = None,
) -> None:
self.fn = fn
if args is None:
args = ()

if kwargs is None:
kwargs = {}

self.fn = fn
self.args = args
self.kwargs = kwargs

def __call__(self, *args, **kwargs) -> R:
call_kwargs = copy(self.kwargs)
call_kwargs.update(kwargs)

if self.args is not None:
args = self.args
fn = partial(self.fn, *self.args, **self.kwargs)

return self.fn(*args, **call_kwargs)
return fn(*args, **kwargs)

def update(self, **kwargs) -> None:
self.kwargs.update(kwargs)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "kaizo"
version = "1.5.2"
version = "1.5.3"
description = "declarative YAML-based configuration parser"
authors = [{ name = "Mohammad Ghazanfari", email = "mgh.5225@gmail.com" }]
readme = "README.md"
Expand Down
46 changes: 46 additions & 0 deletions tests/test_lazy_injection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from pathlib import Path

from kaizo import ConfigParser
from kaizo.utils import FnWithKwargs

X = 5
Y = 6
Z = 7

main_py = f"""
def fn(x,y,z):
return (x,y,z)

def fn2(cb):
return cb({X},{Y})
"""


lazy_config = f"""
local: main.py
a:
module: local
source: fn
lazy: true
args:
z: {Z}
b:
module: local
source: fn2
args:
cb: .{{a}}
"""


def test_lazy_injection(tmp_path: Path) -> None:
module = tmp_path / "main.py"
module.write_text(main_py)

cfg_file = tmp_path / "cfg.yml"
cfg_file.write_text(lazy_config)

parser = ConfigParser(cfg_file, kwargs={"injected": X})
out = parser.parse()

assert isinstance(out["a"], FnWithKwargs)
assert out["b"] == (X, Y, Z)
Loading