Advanced Python / Type Hints

Advanced Python / Type Hints#

  1. 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.

  2. 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" + 3 raises a TypeError rather than producing "53" or 8. 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.

  3. What is duck typing, and how does Protocol formalize 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 (from typing) formalises this concept for static type checkers. You define a Protocol class 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
    
  4. 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 include pyright (used by Pylance in VS Code) and pytype (from Google).

  5. What is the difference between Optional[str] and str? When should each be used?

    str means the value must be a string — it cannot be None. Optional[str] (equivalent to Union[str, None]) means the value is either a string or None.

    Use str when the argument or return value is always present. Use Optional[str] when the value might legitimately be absent — for example, a parameter with a default of None, or a lookup function that returns None when no result is found. Annotating nullable values as Optional forces callers to handle the None case explicitly, which catches many common bugs.

  6. Explain how Union[int, float] and int | float (Python 3.10+) are related. Which should you use in a new project targeting Python 3.10+?

    They are semantically identical. int | float is syntactic sugar introduced in Python 3.10 (PEP 604) that avoids the need to import Union from typing. The | operator on type objects at runtime produces the same Union type that mypy and other checkers recognise.

    For a new project targeting Python 3.10+, prefer int | float — it is more concise and readable. Use Union[int, float] only when you need to support Python 3.9 or earlier (or add from __future__ import annotations to defer evaluation and allow the | syntax on older versions).

  7. What problem does TypeVar solve that cannot be solved with Any? Provide a brief code example illustrating the difference.

    Any loses all type information — a function that accepts Any and returns Any tells the type checker nothing about the relationship between input and output. TypeVar preserves 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
    
  8. 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:
        ...
    
  9. 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.py
    

    A 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: ignore comment — 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.

  10. What does ClassVar signal to a type checker, and how does it differ from a regular instance attribute annotation?

    ClassVar[X] (from typing) 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.03 would be flagged as an error).

    • Ensure the attribute is not treated as an __init__ parameter by tools like dataclasses.

    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 on self inside __init__ and is unique to each object.