Python interview question

Data SciencePythonStructured Outputsmedium

An inventory agent asks an LLM for a JSON reorder decision and passes the fields to a typed helper. This time the model returned units as a string. What happens when the snippet runs?

python
import json

def reorder_qty(units: int, packs: int) -> int:
    return units * packs

out = json.loads('{"units": "12", "packs": 3}')   # LLM output
print(reorder_qty(out["units"], out["packs"]))
  1. AIt prints 36: the units: int annotation makes Python convert the JSON string "12" into an integer when the function is called, the way pydantic coerces a model field.
  2. BIt prints 121212: annotations are not enforced at runtime, so "12" * 3 repeats the string, and the agent receives a wrong quantity without any exception being raised.
  3. CIt raises a TypeError at the call, because the interpreter checks every argument against its annotation before the body runs, so the bad value never reaches the logic.
  4. DIt raises a TypeError inside the function, because multiplying a str by an int is not defined in Python; the error simply appears later than a static checker would show it.
Show the answer and explanation

Correct answer: B, It prints 121212: annotations are not enforced at runtime, so "12" * 3 repeats the string, and the agent receives a wrong quantity without any exception being raised.

Explanation Python

Type hints are metadata. CPython exposes them through __annotations__ but never checks them when a function is called. reorder_qty("12", 3) therefore runs the body with a string, and str * int is valid Python: it repeats the string. The function returns "121212", and an agent that trusts it might order 121,212 units, with no exception anywhere.

Static checkers such as mypy or pyright cannot catch this either, because json.loads returns Any: the wrong type only exists at runtime, in data produced by the model.

The fix is to validate at the boundary where untrusted data enters:

from pydantic import BaseModel

class Reorder(BaseModel):
    units: int
    packs: int

r = Reorder.model_validate_json(raw)   # "12" -> 12, "twelve" -> ValidationError

In its default (lax) mode pydantic coerces a clean numeric string like "12" to an int and raises a ValidationError for values like "twelve"; strict mode rejects strings for int fields altogether. Alternatives are a JSON Schema check or the provider's structured-output mode, still followed by validation and a retry when it fails.

Why the distractors fail: plain annotations never trigger conversion or call-time checks (pydantic coerces "12" only because a model or @validate_call validates the data explicitly), and str * int is defined (it is repetition), which is exactly why the bug is silent.

Interview tip: describe LLM output as untrusted input: parse it, validate it against a schema, apply business range checks (e.g. units between 1 and 500), and retry or escalate to a human when validation fails.

Practice it as a quiz

Answer this and the other free questions with instant grading, streaks and weak-topic tracking, or unlock all 4,000 questions.

More Data Science questions

  1. The chart plots weekly active users of a new GenAI app on a log scale (the y-axis shows log10 of users). How should the change after week 10 be interpreted?
  2. A test ran at 10% treatment on Friday and was ramped to 50% for the weekend. Treatment converts better within each period but worse when the data are pooled…
  3. In PostgreSQL, converted is an INTEGER column holding 0 or 1. This daily conversion-rate query shows 0 for almost every day, and 1 only on days where every…
  4. A retailer's marketing mix model (MMM) transforms weekly TV spend with geometric adstock aₜ = xₜ + λ·aₜ₋₁, with λ = 0.6 and a₀ = 0, and then passes the…
  5. A telecom's plan names are s = pd.Series(["Max+ 10GB", "Max 20GB", None, "Mini 5GB"]). What do print(s.str.contains("Max+", na=False).sum()) and…