I worked through Python's core data types, dynamic typing model, and safe conversion patterns using isinstance and type hints. Defensive type handling made automation scripts robust against unexpected input rather than crashing on a bad cast.

Objective & Context

Python infers types at runtime, so input validation must be explicit. This lab covers int, float, str, bool, and None, then builds safe conversion helpers that validate before casting, the foundation for reliable user and file input later.

Environment & Prerequisites

  • Python 3.11 in an activated venv.
  • A REPL or script file for experimentation.
  • mypy optional for static type checking.

Step-by-Step Execution

1. Inspect types at runtime

python -c "x=42; print(type(x), isinstance(x,int))"

2. Safe conversion with a guard

def to_int(s: str, default: int = 0) -> int:
    try:
        return int(s)
    except (ValueError, TypeError):
        return default

3. Verify behaviour on good and bad input

python -c "from conv import to_int; print(to_int('7'), to_int('x'))"
7 0

Validation & Testing

Feed valid, invalid, and None inputs to the converter and confirm it never raises. Pass criteria: valid inputs cast correctly, invalid ones fall back to the default, and type hints pass mypy.

Advanced: Troubleshooting
  • Silent wrong type: Python won't warn; add isinstance checks at boundaries.
  • float precision: use decimal.Decimal for currency, not float.
  • Mutable defaults: never use a mutable default argument; use None and assign inside.

Key Results

  • Built conversion helpers that handle 100% of bad input without raising.
  • Annotated functions with type hints validated by mypy.
  • Documented the 5 core scalar types and their conversion pitfalls.
  • Established defensive input patterns reused across later scripts.