Skip to content

bind_kwargs

Class info

Classes

Name Children Inherits
BoundFunction
schemez.bind_kwargs
A function with pre-bound parameters.

    🛈 DocStrings

    BoundFunction

    A function with pre-bound parameters.

    This class wraps a function and binds some parameters to fixed values, while updating the signature and docstring to reflect only the remaining parameters that can still be provided when calling.

    Source code in src/schemez/bind_kwargs.py
    class BoundFunction[T]:
        """A function with pre-bound parameters.
    
        This class wraps a function and binds some parameters to fixed values,
        while updating the signature and docstring to reflect only the remaining
        parameters that can still be provided when calling.
        """
    
        def __init__(self, func: Callable[..., T], **bound_kwargs: Any):
            """Initialize with a function and parameters to bind.
    
            Args:
                func: The function to wrap
                **bound_kwargs: Parameters to bind to fixed values
    
            Raises:
                ValueError: If any parameter name is not in the function signature
            """
            self.func = func
            self.bound_kwargs = bound_kwargs
            self.__name__ = get_object_name(func, "unknown")
            self.__module__ = func.__module__
            self.__qualname__ = get_object_qualname(func, "unknown")
            self.__doc__ = remove_kwargs_from_docstring(func.__doc__, self.bound_kwargs)
            self.__annotations__ = self._update_annotations(_get_annotations(func))
            self.__signature__ = self._update_signature()
    
            # Verify all bound kwargs are valid parameters
            sig = get_signature(func)
            for param in bound_kwargs:
                if param not in sig.parameters:
                    name = get_object_name(func, "unknown")
                    msg = f"Parameter {param!r} not found in signature of {name}"
                    raise ValueError(msg)
    
        def __call__(self, *args: Any, **kwargs: Any) -> T:
            """Call the function with the bound parameters.
    
            Args:
                *args: Positional arguments for the function
                **kwargs: Keyword arguments for the function
    
            Returns:
                The return value from the wrapped function
            """
            # Combine bound parameters with provided parameters
            all_kwargs = {**self.bound_kwargs, **kwargs}
            return self.func(*args, **all_kwargs)
    
        def _update_signature(self) -> inspect.Signature:
            """Create a new signature excluding bound parameters.
    
            Returns:
                Updated signature without bound parameters
            """
            sig = get_signature(self.func)
            params = [p for name, p in sig.parameters.items() if name not in self.bound_kwargs]
            return sig.replace(parameters=params)
    
        def _update_annotations(self, annotations: dict[str, Any]) -> dict[str, Any]:
            """Remove bound parameters from annotations.
    
            Args:
                annotations: Original function annotations
    
            Returns:
                Updated annotations dictionary
            """
            return {
                name: ann
                for name, ann in annotations.items()
                if name not in self.bound_kwargs and name != "return"
            }
    

    __call__

    __call__(*args: Any, **kwargs: Any) -> T
    

    Call the function with the bound parameters.

    Parameters:

    Name Type Description Default
    *args Any

    Positional arguments for the function

    ()
    **kwargs Any

    Keyword arguments for the function

    {}

    Returns:

    Type Description
    T

    The return value from the wrapped function

    Source code in src/schemez/bind_kwargs.py
    def __call__(self, *args: Any, **kwargs: Any) -> T:
        """Call the function with the bound parameters.
    
        Args:
            *args: Positional arguments for the function
            **kwargs: Keyword arguments for the function
    
        Returns:
            The return value from the wrapped function
        """
        # Combine bound parameters with provided parameters
        all_kwargs = {**self.bound_kwargs, **kwargs}
        return self.func(*args, **all_kwargs)
    

    __init__

    __init__(func: Callable[..., T], **bound_kwargs: Any)
    

    Initialize with a function and parameters to bind.

    Parameters:

    Name Type Description Default
    func Callable[..., T]

    The function to wrap

    required
    **bound_kwargs Any

    Parameters to bind to fixed values

    {}

    Raises:

    Type Description
    ValueError

    If any parameter name is not in the function signature

    Source code in src/schemez/bind_kwargs.py
    def __init__(self, func: Callable[..., T], **bound_kwargs: Any):
        """Initialize with a function and parameters to bind.
    
        Args:
            func: The function to wrap
            **bound_kwargs: Parameters to bind to fixed values
    
        Raises:
            ValueError: If any parameter name is not in the function signature
        """
        self.func = func
        self.bound_kwargs = bound_kwargs
        self.__name__ = get_object_name(func, "unknown")
        self.__module__ = func.__module__
        self.__qualname__ = get_object_qualname(func, "unknown")
        self.__doc__ = remove_kwargs_from_docstring(func.__doc__, self.bound_kwargs)
        self.__annotations__ = self._update_annotations(_get_annotations(func))
        self.__signature__ = self._update_signature()
    
        # Verify all bound kwargs are valid parameters
        sig = get_signature(func)
        for param in bound_kwargs:
            if param not in sig.parameters:
                name = get_object_name(func, "unknown")
                msg = f"Parameter {param!r} not found in signature of {name}"
                raise ValueError(msg)
    

    remove_kwargs_from_docstring

    remove_kwargs_from_docstring(docstring: str | None, kwargs: dict[str, Any]) -> str | None
    

    Update docstring to remove bound parameters.

    Parameters:

    Name Type Description Default
    docstring str | None

    Original function docstring

    required
    kwargs dict[str, Any]

    kwargs to remove from docstring

    required

    Returns:

    Type Description
    str | None

    Updated docstring with bound parameters removed

    Source code in src/schemez/bind_kwargs.py
    def remove_kwargs_from_docstring(docstring: str | None, kwargs: dict[str, Any]) -> str | None:
        """Update docstring to remove bound parameters.
    
        Args:
            docstring: Original function docstring
            kwargs: kwargs to remove from docstring
    
        Returns:
            Updated docstring with bound parameters removed
        """
        if not docstring:
            return docstring
    
        lines = docstring.splitlines()
        new_lines = []
    
        # Find the Args section and modify it
        in_args_section = False
        skip_lines = False
        current_param = None
    
        for line in lines:
            # Check if entering Args section
            if "Args:" in line:
                in_args_section = True
                new_lines.append(line)
                continue
            if in_args_section and line.strip() and not line.startswith(" "):
                in_args_section = False
            if in_args_section and ":" in line:
                # Get parameter name from the line
                param_name = line.strip().split(":", 1)[0].strip()
                if param_name in kwargs:
                    skip_lines = True
                    current_param = param_name
                else:
                    skip_lines = False
                    current_param = None
            if in_args_section and current_param and line.strip() and ":" in line.lstrip():
                new_param = line.strip().split(":", 1)[0].strip()
                if new_param != current_param:
                    skip_lines = False
                    current_param = None
    
            # Add the line if not skipping
            if not skip_lines:
                new_lines.append(line)
    
        return "\n".join(new_lines)
    

    search_db async

    search_db(
        query: str, k: int = 5, filters: dict[str, list[str]] | None = None, min_score: float = 0.7
    ) -> list[dict[str, Any]]
    

    Search the database for relevant information.

    Parameters:

    Name Type Description Default
    query str

    Search query text

    required
    k int

    Number of results to return

    5
    filters dict[str, list[str]] | None

    Filters to apply to search 2nd line

    None
    min_score float

    Minimum relevance score

    0.7

    Returns:

    Type Description
    list[dict[str, Any]]

    List of search results

    Example

    await search_db("quantum computing", k=3)

    Source code in src/schemez/bind_kwargs.py
    async def search_db(
        query: str,
        k: int = 5,
        filters: dict[str, list[str]] | None = None,
        min_score: float = 0.7,
    ) -> list[dict[str, Any]]:
        """Search the database for relevant information.
    
        Args:
            query: Search query text
            k: Number of results to return
            filters: Filters to apply to search
                     2nd line
            min_score: Minimum relevance score
    
        Returns:
            List of search results
    
        Example:
            >>> await search_db("quantum computing", k=3)
        """
        print(f"query={query}, k={k}, filters={filters}, min_score={min_score}")
        return [{"id": 1, "score": 0.9}, {"id": 2, "score": 0.8}]