Advanced Python / Type Hints#
What is the difference between static typing and dynamic typing? In which category does Python fall, and why?
In static typing, a type checker (usually the compiler) verifies type correctness before the program runs. If you pass the wrong type to a function, the program will not compile. Languages like Java, C, and C++ are statically typed.
In dynamic typing, type checking happens at runtime. The interpreter determines whether an operation is legal only when that line of code actually executes. Python falls into this category: a variable can hold any value, and you can change what type it holds at any time. A function call with the wrong type will not be caught until Python actually tries to execute the offending operation.
What does it mean to say Python is a “strongly typed” language? How does this differ from “statically typed”?
Strongly typed means the type system is strictly enforced — Python will not silently coerce one type into another. For example,
"5" + 3raises aTypeErrorrather than producing"53"or8. Python will not automatically convert between incompatible types.Statically typed means types are checked before runtime (at compile time). These are independent axes: Python is strongly typed and dynamically typed. It enforces types strictly when code runs, but it does not check types before running.
What is duck typing, and how does
Protocolformalize it within the type system?Duck typing means an object’s suitability for an operation is determined by the presence of the required methods and attributes, not by its explicit type or inheritance hierarchy. The name comes from the saying: “If it walks like a duck and quacks like a duck, it is a duck.”
Protocol(fromtyping) formalises this concept for static type checkers. You define aProtocolclass listing the required method signatures. Any class that implements those methods is automatically considered compatible — no explicit inheritance is needed. This lets mypy verify duck-typed code statically.from typing import Protocol class Quackable(Protocol): def quack(self) -> str: ... class Duck: def quack(self) -> str: return "Quack!" class Person: def quack(self) -> str: return "I'm quacking like a duck!" def make_it_quack(animal: Quackable) -> None: print(animal.quack()) make_it_quack(Duck()) # fine — Duck has quack() make_it_quack(Person()) # fine — Person has quack() too
Why do Python type hints not raise errors at runtime when a wrong type is passed? What tool is needed to catch these errors?
Type annotations in Python are stored as metadata (in
__annotations__) but are deliberately not enforced by the interpreter at runtime. The language designers chose this approach to keep type hints opt-in and to avoid performance overhead. Existing code with no annotations continues to run unchanged.To catch type mismatches you need a static type checker such as
mypy. mypy analyses your source files without executing them and reports errors based on the declared annotations. Other options includepyright(used by Pylance in VS Code) andpytype(from Google).What is the difference between
Optional[str]andstr? When should each be used?strmeans the value must be a string — it cannot beNone.Optional[str](equivalent toUnion[str, None]) means the value is either a string orNone.Use
strwhen the argument or return value is always present. UseOptional[str]when the value might legitimately be absent — for example, a parameter with a default ofNone, or a lookup function that returnsNonewhen no result is found. Annotating nullable values asOptionalforces callers to handle theNonecase explicitly, which catches many common bugs.Explain how
Union[int, float]andint | float(Python 3.10+) are related. Which should you use in a new project targeting Python 3.10+?They are semantically identical.
int | floatis syntactic sugar introduced in Python 3.10 (PEP 604) that avoids the need to importUnionfromtyping. The|operator on type objects at runtime produces the sameUniontype that mypy and other checkers recognise.For a new project targeting Python 3.10+, prefer
int | float— it is more concise and readable. UseUnion[int, float]only when you need to support Python 3.9 or earlier (or addfrom __future__ import annotationsto defer evaluation and allow the|syntax on older versions).What problem does
TypeVarsolve that cannot be solved withAny? Provide a brief code example illustrating the difference.Anyloses all type information — a function that acceptsAnyand returnsAnytells the type checker nothing about the relationship between input and output.TypeVarpreserves that relationship: it says “whatever type goes in, the same type comes out.”from typing import Any, TypeVar T = TypeVar('T') def first_any(items: list[Any]) -> Any: return items[0] def first_typed(items: list[T]) -> T: return items[0] # With Any, the checker cannot infer the return type x = first_any([1, 2, 3]) # x is Any — no autocomplete, no error detection # With TypeVar, the checker knows the return type matches the input y = first_typed([1, 2, 3]) # y is int — full type safety preserved z = first_typed(["a", "b"]) # z is str
What is a type alias? Give an example where creating a type alias improves code readability.
A type alias is a name assigned to a type expression so it can be reused throughout the code without repeating the full expression. It does not create a new type; it is purely a shorthand.
Without an alias, a function dealing with financial portfolios might look like:
def rebalance(portfolio: dict[str, float], targets: dict[str, float]) -> dict[str, float]: ...
With a type alias the intent is immediately clear:
Portfolio = dict[str, float] # ticker -> weight def rebalance(portfolio: Portfolio, targets: Portfolio) -> Portfolio: ...
Describe how to run mypy on a file and what a typical error message looks like. How would you suppress a false positive on a single line?
Run mypy from the terminal:
mypy script.pyA typical error message has the form:
script.py:8: error: Argument 1 to "add_funds" has incompatible type "str"; expected "float" [arg-type]
This tells you the file name, line number, a human-readable description, and the error code in brackets.
To suppress a false positive on a single line, add a
# type: ignorecomment — preferably with the specific error code:result = legacy_function(data) # type: ignore[arg-type]
The error-code form is preferred because it documents why the suppression was added and still catches unrelated errors on that line.
What does
ClassVarsignal to a type checker, and how does it differ from a regular instance attribute annotation?ClassVar[X](fromtyping) tells the type checker that an attribute belongs to the class itself rather than to individual instances. The checker will then:Prevent assignment to that attribute through an instance (e.g.,
obj.rate = 0.03would be flagged as an error).Ensure the attribute is not treated as an
__init__parameter by tools likedataclasses.
from typing import ClassVar class BankAccount: interest_rate: ClassVar[float] = 0.02 # belongs to the class balance: float # belongs to each instance def __init__(self, balance: float) -> None: self.balance = balance acct = BankAccount(1000.0) # acct.interest_rate = 0.03 # mypy error: cannot assign to ClassVar via instance BankAccount.interest_rate = 0.03 # allowed: assigned through the class
A regular instance annotation (without
ClassVar) is expected to be set onselfinside__init__and is unique to each object.