Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What is dynamic typing?
What you need to know
Names point at objects
In Python, x = 10 does not create a box called x that only holds integers. It creates an int object with the value 10, and makes the name x point at it. Rebinding the name to something else is always allowed:
1x = 102print(type(x)) # <class 'int'>3x = "ten"4print(type(x)) # <class 'str'>The object 10 still knows it is an int. Only the name moved.
Two separate questions: static or dynamic, strong or weak
- Static vs dynamic — when are types checked? Static languages (Java, Rust, Go) check before running. Dynamic languages (Python, JavaScript) check while running.
- Strong vs weak — does the language silently convert mismatched types? Python refuses; JavaScript converts, so
"5" + 5is"55"there.
1print("5" * 3) # 555 -> str * int is defined: repetition2try:3 print("5" + 5)4except TypeError as e:5 print(e) # can only concatenate str (not "int") to str6print(int("5") + 5) # 10 -> you convert explicitlyType hints: documentation that tools can check
1def double(x: int) -> int:2 return x * 234print(double(4)) # 85print(double("ab")) # abab -> no error: hints are not checked at runtimeType hints (int, list[float], dict[str, int], str | None) do nothing at runtime — Python happily calls double with a string. Their value is that a type checker such as mypy or pyright reads them before the code runs and reports mismatches, and your editor uses them for autocomplete. Modern syntax: built-in generics like list[str] work from Python 3.9, and X | None from 3.10.
A real-life example
You load a CSV of card transactions and total the amounts. The csv module returns every field as a str, but nothing tells you that until the code runs:
1import csv, io23data = io.StringIO("txn_id,amount\nT1,499.00\nT2,120.50\n")4rows = list(csv.DictReader(data))56total = 07try:8 for row in rows:9 total += row["amount"] # row["amount"] is the str "499.00"10except TypeError as e:11 print("Bug:", e) # Bug: unsupported operand type(s) for +=: 'int' and 'str'1213total = sum(float(row["amount"]) for row in rows)14print(total) # 619.5In a nightly job this crash would happen at 2 a.m., on the server. With a hint like def total(rows: list[dict[str, str]]) -> float, mypy flags the int + str mix in the pull request instead.
Follow-up questions to expect
- "Do type hints make Python faster or enforce types?" — No. CPython ignores them at runtime. Tools like mypy use them, and libraries like Pydantic and FastAPI read them to validate data.
- "What is duck typing?" — Caring about what an object can do, not what class it is. If it has a
.read()method, you can treat it like a file. - "What are the benefits of dynamic typing?" — Less code, fast prototyping in notebooks, and flexible functions that work on many types.