💻 Module: 03-Functions-Modules • Unabridged Executed Lesson
📑 Download Module Slides (PDF) 🐍 Download Notebook (.ipynb)

Lesson 11: Default Arguments, Keyword Calls & Guarding Against Classic Python Argument Bugs

The “Boring Stuff” Problem: 11-Argument Dispersion Formulas You Keep Mis-Ordering

In atmospheric dispersion, calculating ground-level plume concentration downstream of an industrial smoke stack needs emission rate \(Q\), wind speed \(u\), effective stack height \(H_e\), distance \(x\), crosswind offset \(y\), and Pasquill-Gifford stability class ("A".."F"). Passing 7 positional numbers (plume(15.0, 4.0, 65.0, 1200, 0, "D", 0)) makes it hopelessly easy to swap \(u\) and \(H_e\) without noticing!

Default values + Keyword arguments make engineering calls self-documenting:

c_ug_m3 = gaussian_plume(x_m=1500.0, Q_g_s=45.0, u_ms=3.5, H_eff_m=60.0, stab_class="C")

Wait—default y_m=0.0, z_m=0.0 fills centerline ground-level automatically unless overridden!

Watch Out! Never Use a Mutable Default (def log_bad(val, items=[]):)

In Python, default arguments are created ONLY ONCE when def runs—NOT each time you call the function! If you write items=[], every new site or monitoring run secretly appends onto the previous site’s list! Always write items=None and initialize if items is None: items = [].

import math

# Example 1 (Atmospheric Dispersion Modeling): Pasquill-Gifford Gaussian Plume Function
# Cross-reference: Martin / Briggs Urban & Rural Rural Plume Spread Formulas (Seinfeld & Pandis)
_PG_COEFFS = {
    "A": (0.22, 0.20), "B": (0.16, 0.12), "C": (0.11, 0.08),
    "D": (0.08, 0.06), "E": (0.06, 0.03), "F": (0.04, 0.016),
}

def pasquill_gifford_sigmas(x_m: float, stab_class: str = "D") -> tuple[float, float]:
    '''Return horizontal sigma_y [m] and vertical sigma_z [m] using Briggs rural curves.'''
    if x_m <= 0.0:
        raise ValueError("Downwind distance x_m must be strictly > 0.")
    key = stab_class.upper().strip()
    if key not in _PG_COEFFS:
        raise ValueError(f"Unknown Pasquill-Gifford class '{stab_class}'; use A..F.")
    ay, az = _PG_COEFFS[key]
    sigma_y = ay * x_m / math.sqrt(1.0 + 0.0001 * x_m)
    sigma_z = az * x_m / (1.0 + 0.0002 * x_m) if key in {"C", "D"} else az * x_m / math.sqrt(1.0 + 0.0003 * x_m)
    return sigma_y, sigma_z

def gaussian_plume_ground(x_m: float, Q_g_s: float, u_ms: float = 4.0, H_eff_m: float = 50.0,
                          y_m: float = 0.0, stab_class: str = "D") -> float:
    '''Return ground-level (z=0) pollutant concentration in ug/m^3 with ground reflection.'''
    if x_m <= 0.0:
        return 0.0
    sy, sz = pasquill_gifford_sigmas(x_m, stab_class=stab_class)
    prefactor = (Q_g_s * 1e6) / (math.pi * u_ms * sy * sz)   # g/m^3 * 1e6 -> ug/m^3
    lateral = math.exp(-0.5 * (y_m / sy) ** 2)
    vertical_refl = math.exp(-0.5 * (H_eff_m / sz) ** 2)
    return prefactor * lateral * vertical_refl

print("=== Effect of Atmospheric Stability Class on Ground SO2 Centerline (Q=45 g/s, He=60 m, u=3.5 m/s) ===")
for sc in ["A", "C", "D", "F"]:
    c_500 = gaussian_plume_ground(x_m=500.0, Q_g_s=45.0, u_ms=3.5, H_eff_m=60.0, stab_class=sc)
    c_2000 = gaussian_plume_ground(x_m=2000.0, Q_g_s=45.0, u_ms=3.5, H_eff_m=60.0, stab_class=sc)
    print(f"Class {sc} | C(500 m) = {c_500:7.1f} ug/m^3 | C(2000 m) = {c_2000:7.1f} ug/m^3")
=== Effect of Atmospheric Stability Class on Ground SO2 Centerline (Q=45 g/s, He=60 m, u=3.5 m/s) ===
Class A | C(500 m) =   332.4 ug/m^3 | C(2000 m) =    31.6 ug/m^3
Class C | C(500 m) =   537.5 ug/m^3 | C(2000 m) =   155.4 ug/m^3
Class D | C(500 m) =   341.8 ug/m^3 | C(2000 m) =   255.9 ug/m^3
Class F | C(500 m) =     0.0 ug/m^3 | C(2000 m) =   133.0 ug/m^3
# Example 2: Demonstrating Mutable Default Trap vs Clean None Pattern in Lab Batch Logger
def record_grab_good(site_name: str, val_mgL: float, log: list | None = None) -> list:
    if log is None:
        log = []
    log.append((site_name, val_mgL))
    return log

river_a = record_grab_good("NorthFork", 4.2)
river_b = record_grab_good("SouthFork", 8.9)   # Separate list guaranteed!
print("Separate logs verified:", river_a, "|", river_b)
Separate logs verified: [('NorthFork', 4.2)] | [('SouthFork', 8.9)]

Concept Check Questions

  1. Look at the stability table above: why is Class A (very unstable sunny midday convection) much higher right near the stack at 500 m, while Class F (calm night inversion) hits tiny values at 500 m yet climbs further downwind?
  2. Why does Python require positional arguments to come before keyword arguments in func(x, u_ms=4.0)?
  3. What happens if a caller passes stab_class="G" into pasquill_gifford_sigmas?

Guided Practice Problem 1: Downwind Maximum Concentration Search (gaussian_plume_ground)

Write a short loop calling gaussian_plume_ground(..., Q_g_s=45.0, u_ms=3.5, H_eff_m=60.0, stab_class="D") across \(x \in [200, 300, \dots, 5000]\text{ m}\) to locate the peak centerline distance \(x_{\max}\) and maximum SO2 concentration (\(\mu\text{g/m}^3\)), and compare it to the EPA 1-hour SO2 standard (\(196\,\mu\text{g/m}^3\)).

# Guided Practice 1 Starter
best_c, best_x = -1.0, 0
for xm in range(200, 5001, 100):
    c_val = gaussian_plume_ground(x_m=float(xm), Q_g_s=45.0, u_ms=3.5, H_eff_m=60.0, stab_class="D")
    if c_val > best_c:
        best_c, best_x = c_val, xm
print(f"Peak Class D Ground SO2 = {best_c:.1f} ug/m^3 at x = {best_x} m (EPA 1-hr Limit 196 ug/m^3)")
Peak Class D Ground SO2 = 561.3 ug/m^3 at x = 800 m (EPA 1-hr Limit 196 ug/m^3)