from typing import Callable, ParamSpec, TypeVar, Any
# 1. Define ParamSpec and TypeVar
# P will capture the *remaining* parameters of the plotting function after data
P = ParamSpec('P')
# R will capture the return type of the plotting function
R = TypeVar('R')
# 2. Define the plotting function (the target)
def plot(x_data: list[float], y_data: list[float], title: str = "My Plot", color: str = "blue", line_style: str = "--") -> None:
"""
A simple plotting function that takes x, y data and optional styling parameters.
"""
print(f"--- Plotting ---")
print(f"Title: {title}")
print(f"Color: {color}, Line Style: {line_style}")
print(f"First few X values: {x_data[:3]}")
print(f"First few Y values: {y_data[:3]}")
print(f"----------------\n")
# 3. Define the data loading function (part of `load_and_plot`'s 'own' params)
def load_data(file_path: str) -> tuple[list[float], list[float]]:
"""Simulates loading numerical data from a file path."""
print(f"Loading data from '{file_path}'...")
# In a real application, you'd read from a file, database, API, etc.
return [1.0, 2.0, 3.0, 4.0, 5.0], [10.0, 11.0, 12.0, 13.0, 14.0]
# 4. Define `load_and_plot` using ParamSpec
def load_and_plot(
file_path: str,
# plot_func: The function that will actually do the plotting.
# Its signature is Callable[[x_data, y_data, P], R].
# This means it expects two list[float] positional arguments first,
# followed by whatever P captures (positional and keyword args),
# and it returns R.
plot_func: Callable[[list[float], list[float], P], R],
*args: P.args, # These positional args must match the 'P' part of plot_func
**kwargs: P.kwargs # These keyword args must match the 'P' part of plot_func
) -> R:
"""
Loads data from `file_path`, then calls `plot_func` with the loaded data
and any additional `*args` and `**kwargs` provided.
"""
x_data, y_data = load_data(file_path)
# Now, call the plotting function, supplying the loaded data explicitly
# and forwarding the rest of the arguments captured by P.
return plot_func(x_data, y_data, *args, **kwargs)
# --- Usage Example ---
# Example 1: Calling with default plotting parameters (only providing path and function)
print("--- Example 1: Basic Plot ---")
load_and_plot("sales_data.csv", plot)
# Mypy (or other type checkers) will correctly infer that no extra args are needed for `plot`
# since `x_data` and `y_data` are handled by `load_and_plot`, and `title`, `color`, `line_style` have defaults.
# Example 2: Calling with custom plotting parameters (forwarded via ParamSpec)
print("--- Example 2: Custom Plot ---")
load_and_plot(
"temp_data.txt",
plot,
title="Temperature Readings", # This is passed through P.kwargs
color="green", # This is passed through P.kwargs
line_style="-" # This is passed through P.kwargs
)
# Mypy will ensure 'title', 'color', 'line_style' are valid parameters for `plot`
# after `x_data` and `y_data` are accounted for.
# Example 3: Demonstrating type checking errors
print("--- Example 3: Type Checking (Mypy) ---")
try:
# This would cause a type error (e.g., "Unexpected keyword argument 'invalid_param'")
# if you run this with Mypy:
# load_and_plot("financial_data.xlsx", plot, invalid_param="oops")
print("Attempting to call with invalid param (will show type error with Mypy)...")
# To run this line and see runtime error (without Mypy):
# load_and_plot("financial_data.xlsx", plot, invalid_param="oops")
print("... (Skipped runtime error for demonstration)")
except TypeError as e:
print(f"Runtime error (expected with Mypy): {e}")
try:
# This would cause a type error (e.g., "Too many positional arguments for 'plot'")
# if you run this with Mypy:
# load_and_plot("stock_data.json", plot, "Stock Performance")
print("Attempting to call with positional arg instead of keyword (will show type error with Mypy)...")
# To run this line and see runtime error (without Mypy):
# load_and_plot("stock_data.json", plot, "Stock Performance")
print("... (Skipped runtime error for demonstration)")
except TypeError as e:
print(f"Runtime error (expected with Mypy): {e}")