smartyfy.mrindigi.com

Python Master Course V2 — 059. Function Contracts, Type Hints and Docstrings

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 06 · LESSON 059 / 200

Function Contracts, Type Hints and Docstrings

Estimated study: 60–90 minutes. Prerequisite: Lesson 58, plus Python variables, collections, conditions and loops.

Course hub

Video lesson

Video not yet available. This is a reserved video link/player location.

Learning objectives

Document inputs, outputs and errors. Explain the concepts in your own words, implement the pattern, predict output, test boundary conditions, and refactor for readability.

Concepts and professional approach

Document inputs, outputs and errors. A function creates a reusable abstraction: it accepts inputs, performs a focused responsibility, and may return an output. Prefer small named functions with clear contracts. Validate external inputs at system boundaries, choose meaningful names, and separate calculation from printing so functions can be tested. Avoid hidden state where possible. Study the example, then change the inputs and explain the result.

Professional design checklist: define the purpose; choose inputs and outputs; consider invalid and edge-case values; write a minimal implementation; test normal, boundary and failure paths; then document the contract.

Understand and apply: Function Contracts, Type Hints and Docstrings

A contract describes observable behavior

A function contract states what callers may supply, what they receive, which errors can occur, and which side effects are intentional. It is more specific than a function name. For example, a quantity might be an integer but still be unacceptable because it is zero or negative. A returned total might be in whole cents rather than currency units. Document these details so callers do not need to inspect the implementation to use the function correctly.

Type hints describe expected types for readers, editors, and static analysis tools. They do not normally enforce types when Python executes a call. A static checker can report a call that violates an annotation without running that call; runtime validation checks actual values during execution. Neither approach automatically proves business correctness. A type checker can know that quantity is int without knowing whether your application allows zero.

Python code

def repeat_text(text: str, count: int) -> str:
    """Return text repeated count times."""
    return text * count

print(repeat_text("ha", 2))
print(repeat_text(3, 2))

Expected output

haha
6

The second call disagrees with the text annotation and would ordinarily be flagged by a suitably configured static checker. Plain Python nevertheless performs integer multiplication and returns 6, which also disagrees with the return annotation. This demonstrates why annotations are not runtime guards. No checker execution is required to observe the distinction, and diagnostic wording depends on the checker and its configuration.

Write one small, complete invoice-helper contract

Use integer cents for this preparatory helper so its type and unit rules are easy to inspect. Price cents must be a nonnegative built-in integer, quantity must be a positive built-in integer, and booleans are rejected for both. The result is an integer count of cents. The function neither prints nor changes external state. A docstring is the string literal immediately inside the function body; tools can retrieve it through the function object.

Python code

def line_total_cents(price_cents: int, quantity: int) -> int:
    """Return the total in whole cents without changing external state.

    price_cents must be a nonnegative built-in int.
    quantity must be a positive built-in int. Booleans are rejected.
    Raise TypeError for unsupported types and ValueError for invalid values.
    """
    if type(price_cents) is not int or type(quantity) is not int:
        raise TypeError("price_cents and quantity must be integers")
    if price_cents < 0 or quantity <= 0:
        raise ValueError("price must be nonnegative and quantity positive")
    return price_cents * quantity

print(line_total_cents(1950, 3))
assert line_total_cents(0, 1) == 0
assert line_total_cents(1950, 3) == 5850

Expected output

5850

Notice that price zero is valid while quantity zero is not. Two inputs sharing the same type need not share the same range. The error order is deliberate: validate types before ordering comparisons, then validate values, then calculate. Explicit exceptions remain active when Python runs with optimization options; assertions may be disabled, so they are useful for tests but unsuitable as the only protection against bad external input.

Turn promises into checks

Append this check after the complete line_total_cents definition above. It depends on that function.

Python test fragment

try:
    line_total_cents(100, 0)
except ValueError as error:
    print(type(error).__name__)
else:
    raise AssertionError("zero quantity should be rejected")

Expected output

ValueError

The else branch makes the test fail if the expected exception never occurs. An unrelated exception is not swallowed. Keep documentation, annotations, validation, and tests aligned when the contract changes. For instance, allowing refunds would require an explicit negative-quantity policy and new tests, not merely deleting a guard. The next capstone introduces Decimal prices and rounding; its units and permitted inputs must be documented just as precisely.

Progressive runnable Python example

Requires Python 3.10+. Save as lesson59.py, run with python lesson59.py or python3 lesson59.py.

def square(value: int) -> int:
    '''Return the square of an integer.'''
    return value * value
print(square(7))

Expected output:

49

The annotated square is a minimal demonstration with no runtime type guard. Its documented intended input is an integer; Python itself does not enforce that annotation. Compare it with the validated invoice helper above.

Additional exploration

Run the example with different valid inputs. Predict the result before executing. Extract repeated operations into a named function and write at least one assertion for the expected output. For invalid inputs, decide whether to return a documented result or raise an informative exception.

Guided practical project

Document and test a reusable invoice helper. Start with a short requirements table identifying inputs, outputs and validation rules. Implement the smallest working function first, add a separate caller, and test at least three scenarios: typical input, boundary input and invalid input. Print a labeled report only at the program’s outermost layer.

Acceptance criteria: results are deterministic for the same inputs; no unexpected shared mutable state; invalid input is handled deliberately; output is documented; at least three assertions are included in your local project.

Common mistakes and debugging

  • Confusing print with return; printing does not pass a value back to the caller.
  • Using ambiguous names or overly long functions; divide responsibilities clearly.
  • Assuming all inputs are valid; validate values at appropriate boundaries.
  • Relying on global mutable variables; pass dependencies explicitly.
  • Skipping edge-case tests; test zero, empty, negative or missing values as applicable.

Practice and explained answers

Try each question before opening its answer. These self-checks do not record course completion.

Optional hint for question 1

Think about which parts are documentation and which parts execute guards.

1. Why can repeat_text(3, 2) return an integer despite its annotations?

Answer and reasoning: Annotations do not automatically inspect or convert runtime arguments. The actual operation is 3 multiplied by 2. A static checker can flag the incompatible call, while explicit validation would be needed to reject it at runtime.

2. What does -> int tell callers, and what does it not guarantee?

Answer and reasoning: It declares the intended return type for readers and type-checking tools. It does not automatically verify the returned object, indicate the unit, or guarantee a valid value. The docstring must explain that this helper returns whole cents.

3. Why are line_total_cents(0, 1) and line_total_cents(100, 0) treated differently?

Answer and reasoning: A free item is permitted by the nonnegative-price rule, so the first returns 0. A zero quantity violates the positive-quantity rule, so the second raises ValueError. Contract boundaries are parameter-specific.

4. Where must a function docstring appear?

Answer and reasoning: It must be the first statement in the function body, expressed as a string literal. A later standalone string is not assigned as that function’s docstring. Comments may precede the literal because comments are not statements.

5. Why not replace every validation guard with assert?

Answer and reasoning: Assertions can be removed when Python runs with optimization enabled. External-input validation must still run then. Use explicit TypeError or ValueError guards for the contract and assertions for development checks of expected behavior.

Mastery checkpoint

Before moving on, explain the lesson concept, run the example, complete the project, write three tests, and explain why your function design is maintainable. The five-question self-check above provides answer explanations; it does not store account-level completion.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.