How to export Python function call parameters as YAML

Use this decorator:

import functools
import inspect
import yaml
import sys

def print_params_as_yaml(key_arg, file_obj=sys.stdout):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # Get the function signature
            sig = inspect.signature(func)
            # Bind the arguments to the function signature
            bound_arguments = sig.bind(*args, **kwargs)
            # Convert the bound arguments to a dictionary
            params = dict(bound_arguments.arguments)
            
            # Extract the value of the key_arg
            if key_arg not in params:
                raise ValueError(f"The key argument '{key_arg}' is not provided in the function call.")
            
            key_value = params.pop(key_arg)
            # Add the function name to the parameters
            params['func'] = func.__name__
            yaml_dict = {key_value: params}
            
            # Convert the parameters dictionary to YAML format
            params_yaml = yaml.dump(yaml_dict, default_flow_style=False)
            
            # Print or write the parameters in YAML format
            file_obj.write(params_yaml)
            file_obj.write('\n\n')
            
            # Execute the function
            return func(*args, **kwargs)
        
        return wrapper
    return decorator

key_arg is the function parameter to use

Example usage:

# Example usage:
@print_params_as_yaml(key_arg='a')
def example_function(a, b, c=3, d=4):
    return b + c + d

# Test the decorator
example_function("foo", 2, d=5)

# Prints
# foo:
#   b: 2
#   d: 5
#   func: example_function