Lesson 08: Flexible Arguments (*args, **kwargs), Keyword Safety & Built-In Modules

The “Boring Stuff” Problem: Argument Order Confusion & Reinventing the Wheel

Imagine calling tank_force(2.5, 1.6, 3.0, 55.0). Quick—was 2.5 the gate width or the height? Was 3.0 top depth or density? Mixing up two positional numbers silently outputs a plausible-looking wrong bridge load!

Python solves this cleanly with keyword arguments, default parameters, *args / **kwargs, and its “Batteries Included” standard library (math, statistics, datetime).


Positional vs. Keyword vs. Default Arguments

  1. Positional Arguments: Matched strictly left-to-right (calc(10, 20)). Great for 1–2 obvious inputs like sin(x).
  2. Keyword Arguments: Named explicitly at call time (tank_force(width_m=2.5, height_m=1.6, top_depth_m=3.0, tilt_deg=55.0)). Now argument order never causes silent unit swaps!
  3. Default Parameter Values: Give common engineering constants sensible defaults (rho=998.0, g=9.80665) that callers only override when working with oil or on Mars.
  4. Arbitrary *args and **kwargs:
    • *args packs any number of positional arguments into a tuple (great for summing parallel thermal resistances R_total(*resistances) regardless of whether a furnace wall has 2 layers or 8 layers!).
    • **kwargs packs extra named configuration pairs into a dictionary.

Watch Out! Mutable Default Arguments Bug (def add_sensor(log=[]):)

Never write def f(items=[]): in Python! Default lists are created once when Python defines the function—so every later call shares and pollutes the same list! Always write def f(items=None): and create items = [] if items is None else items inside.

import math
import statistics

# Example 1 (*args for Arbitrary Multi-Layer Conduction Wall — Heat Transfer Module 1):
def series_thermal_resistance(*layer_tuples):
    '''Sum 1D conduction resistances (L_m / k_W_mK) for ANY number of wall layers!
    Each argument is a (thickness_m, k_W_mK) tuple.
    '''
    R_total = 0.0
    for idx, (L_m, k_val) in enumerate(layer_tuples, 1):
        R_i = L_m / k_val
        R_total += R_i
    return R_total

# Works seamlessly for 2 layers OR 4 layers without rewriting the function!
R_double_wall = series_thermal_resistance((0.012, 50.0), (0.080, 0.042))
R_furnace_4 = series_thermal_resistance((0.12, 1.1), (0.10, 0.045), (0.05, 0.038), (0.008, 45.0))
print(f"2-Layer Insulated Wall R'' : {R_double_wall:.4f} m^2*K/W")
print(f"4-Layer Furnace Wall R''   : {R_furnace_4:.4f} m^2*K/W")


# Example 2 (Solar Thermal Module 1 + Statistics): Solar Geometry & Irradiance QC
def solar_declination_and_hour_angle(day_of_year: int, solar_hour: float) -> tuple[float, float]:
    '''Cooper equation for solar declination delta [deg] and hour angle omega [deg].'''
    delta_deg = 23.45 * math.sin(math.radians(360.0 * (284 + day_of_year) / 365.0))
    omega_deg = 15.0 * (solar_hour - 12.0)   # 15 deg per hour from solar noon
    return delta_deg, omega_deg

delta_jun21, om_14 = solar_declination_and_hour_angle(day_of_year=172, solar_hour=14.5)
print(f"\nSummer Solstice Declination : {delta_jun21:+.2f} deg | 14:30 Hour Angle : {om_14:+.1f} deg")

# Using built-in statistics module on 7 replicate tensile yield readings [MPa]
yield_samples_mpa = [274.2, 276.8, 273.5, 275.9, 277.1, 274.8, 275.0]
print(f"Material Coupon Mean Sy = {statistics.mean(yield_samples_mpa):.2f} MPa, Std Dev = {statistics.stdev(yield_samples_mpa):.2f} MPa")
2-Layer Insulated Wall R'' : 1.9050 m^2*K/W
4-Layer Furnace Wall R''   : 3.6473 m^2*K/W

Summer Solstice Declination : +23.45 deg | 14:30 Hour Angle : +37.5 deg
Material Coupon Mean Sy = 275.33 MPa, Std Dev = 1.33 MPa

Lambda Functions (lambda = Quick One-Line Helper) & Keyword Packing

Sometimes a SciPy solver or sorted() needs a 1-line mathematical rule without writing a full 4-line def block. A lambda builds a tiny anonymous function right inline: pressure_pa = lambda T_k: (m * R * T_k) / V. Keep lambdas strictly short and simple—if logic needs an if/elif or more than 1 expression, use a normal def with a docstring!


Practice Questions (Concept Check)

  1. Can a positional argument appear after a keyword argument in a function call like calc(rho=998, 0.05)?
  2. Why does def record(data=[]): cause mysterious bugs across multiple function calls, and what is the idiomatic fix?
  3. Explain the difference between *args and **kwargs in a function definition.
  4. Why might keyword arguments (D=0.08, L=120.0) prevent fatal unit/geometry swaps in engineering design scripts?

Guided Practice Problem 1 (Worked Self-Check): Parallel Pipe/Resistor Equivalence Function (*args)

In Heat Transfer (parallel composite conduction) AND Fluid Mechanics (parallel pipe flow conductances), total conductance is \(C_{\text{tot}} = \sum G_i\) and overall resistance is \(R_{\text{eq}} = \left(\sum_{i=1}^N \frac{1}{R_i}\right)^{-1}\). Write a function parallel_resistance(*r_values) accepting ANY number of parallel resistances, verify on three wall studs vs. insulation paths [0.25, 4.2, 4.2] \(\text{K/W}\), and return R_eq.

Hint: 1.0 / sum(1.0 / r for r in r_values)

Raise ValueError if *r_values is empty or any resistance <= 0.

# Worked Practice Problem 1 Solution: General *args Parallel Thermal Network
def parallel_resistance(*r_values: float) -> float:
    '''Return equivalent resistance for any number of parallel thermal paths.'''
    if not r_values:
        raise ValueError("Provide at least one resistance.")
    if any(r <= 0 for r in r_values):
        raise ValueError("All resistances must be > 0.")
    return 1.0 / sum(1.0 / r for r in r_values)

R_eq_stud_wall = parallel_resistance(0.25, 4.2, 4.2)
print(f"Composite Stud-Insulation R_eq = {R_eq_stud_wall:.4f} K/W")
print(f"Two Equal Paths Check (4.0 || 4.0) = {parallel_resistance(4.0, 4.0):.4f} K/W")
Composite Stud-Insulation R_eq = 0.2234 K/W
Two Equal Paths Check (4.0 || 4.0) = 2.0000 K/W

End-of-Chapter Practice Problems (Try Yourself!)

  1. Flexible Gas Compressor Power (**kwargs): Write compressor_power(m_dot_kg_s, P1_bar, P2_bar, **gas_props) using default gas_props (T1_k=298.15, gamma=1.4, cp=1.005, eta_c=0.84) so a caller can override only specific properties like gamma=1.667, cp=5.19 for Helium!
  2. Sorting Turbines by Efficiency (lambda + sorted): Sort a list of (turbine_name, eta_pct, net_mw) tuples in descending order of thermal efficiency using sorted(..., key=lambda row: row[1], reverse=True).
  3. Cantilever Beam Statistical QC (statistics): Compute the sample mean, median, and standard deviation of the measured laser deflections in datasets/Solids_Cantilever_Beam_Deflection_Data.csv.

🎬 Concept & Engineering Animation

🎬 Keyword Args And Solar Geometry