MIL-004: first-class functions and decorators #35

Merged
Tirsvad merged 3 commits from mil-004-functions-decorators into main 2026-11-06 05:53:53 +01:00
5 changed files with 243 additions and 0 deletions
Showing only changes of commit ca46c11c9b - Show all commits

No files matched your search

+23
View File
@@ -38,3 +38,26 @@ CLI_COMMANDS: Final[tuple[tuple[str, str, str, bool, str], ...]] = (
NO_CONFIRMATION_WARNING,
),
)
## @brief Message returned by the nested function of lecture 5.
NESTED_FUNCTION_MESSAGE: Final[str] = "Hello from the nested function"
## @brief Demo line templates of lecture 5; `{value}` is the printed result.
ADD_DEMO_LINE: Final[str] = "calculate(add, 2, 3) = {value}"
SUBTRACT_DEMO_LINE: Final[str] = "calculate(subtract, 5, 3) = {value}"
OUTER_DEMO_LINE: Final[str] = "outer_function() = {value}"
RETURNED_DEMO_LINE: Final[str] = "returned nested function() = {value}"
## @brief HTML tag names used by the lecture 6 decorators.
BOLD_TAG: Final[str] = "b"
EMPHASIS_TAG: Final[str] = "em"
UNDERLINE_TAG: Final[str] = "u"
## @brief Template wrapping text in an HTML tag.
HTML_TAG_TEMPLATE: Final[str] = "<{tag}>{text}</{tag}>"
## @brief Demo line templates of lecture 6; `{value}` is the printed result.
PLAIN_DEMO_LINE: Final[str] = "plain: {value}"
BY_HAND_DEMO_LINE: Final[str] = "by hand, make_bold(plain_hello)(): {value}"
AT_SYNTAX_DEMO_LINE: Final[str] = "@ syntax, say_hello(): {value}"
NAME_DEMO_LINE: Final[str] = "say_hello.__name__: {value}"
+69
View File
@@ -0,0 +1,69 @@
## @file decorators.py
# @brief Lecture 6 demo of decorators and the `@` syntax.
"""A decorator wraps a function to add behaviour without editing it."""
from collections.abc import Callable
from functools import wraps
from flask_day_54.domain.constants import (
AT_SYNTAX_DEMO_LINE,
BOLD_TAG,
BY_HAND_DEMO_LINE,
EMPHASIS_TAG,
GREETING,
HTML_TAG_TEMPLATE,
NAME_DEMO_LINE,
PLAIN_DEMO_LINE,
UNDERLINE_TAG,
)
def _tag_decorator(tag: str) -> Callable[[Callable[[], str]], Callable[[], str]]:
"""Build a decorator that wraps the returned text in the given HTML tag."""
def decorator(func: Callable[[], str]) -> Callable[[], str]:
@wraps(func)
def wrapper() -> str:
return HTML_TAG_TEMPLATE.format(tag=tag, text=func())
return wrapper
return decorator
## @brief Wrap the text of a function in `<b>` tags.
make_bold = _tag_decorator(BOLD_TAG)
## @brief Wrap the text of a function in `<em>` tags.
make_emphasis = _tag_decorator(EMPHASIS_TAG)
## @brief Wrap the text of a function in `<u>` tags.
make_underlined = _tag_decorator(UNDERLINE_TAG)
## @brief Greeting with the three decorators stacked; the nearest applies first.
@make_bold
@make_emphasis
@make_underlined
def say_hello() -> str:
"""Return the greeting."""
return GREETING
## @brief The same greeting without any decorator.
def plain_hello() -> str:
"""Return the greeting."""
return GREETING
## @brief Print the lecture 6 demo.
def main() -> None:
"""Print the plain, hand-decorated and `@` decorated greeting."""
print(PLAIN_DEMO_LINE.format(value=plain_hello()))
print(BY_HAND_DEMO_LINE.format(value=make_bold(plain_hello)()))
print(AT_SYNTAX_DEMO_LINE.format(value=say_hello()))
print(NAME_DEMO_LINE.format(value=say_hello.__name__))
if __name__ == "__main__":
main()
@@ -0,0 +1,66 @@
## @file first_class_functions.py
# @brief Lecture 5 demo of functions as first-class objects.
"""Functions can be passed as arguments, nested and returned like any value."""
from collections.abc import Callable
from flask_day_54.domain.constants import (
ADD_DEMO_LINE,
NESTED_FUNCTION_MESSAGE,
OUTER_DEMO_LINE,
RETURNED_DEMO_LINE,
SUBTRACT_DEMO_LINE,
)
## @brief Add two numbers.
def add(n1: float, n2: float) -> float:
"""Return the sum of the two numbers."""
return n1 + n2
## @brief Subtract the second number from the first.
def subtract(n1: float, n2: float) -> float:
"""Return the first number minus the second."""
return n1 - n2
## @brief Apply a function passed as argument to two numbers.
# @param func The function to call with `n1` and `n2`.
def calculate(n1: float, n2: float, func: Callable[[float, float], float]) -> float:
"""Return `func(n1, n2)`."""
return func(n1, n2)
## @brief Call a function that is defined inside this one.
def outer_function() -> str:
"""Return the result of the nested function, reachable only in here."""
def nested_function() -> str:
return NESTED_FUNCTION_MESSAGE
return nested_function()
## @brief Hand the nested function to the caller.
def returns_nested_function() -> Callable[[], str]:
"""Return the nested function so it can be stored and called later."""
def nested_function() -> str:
return NESTED_FUNCTION_MESSAGE
return nested_function
## @brief Print the lecture 5 demo.
def main() -> None:
"""Print the results of the first-class function examples."""
print(ADD_DEMO_LINE.format(value=calculate(2, 3, add)))
print(SUBTRACT_DEMO_LINE.format(value=calculate(5, 3, subtract)))
print(OUTER_DEMO_LINE.format(value=outer_function()))
stored = returns_nested_function()
print(RETURNED_DEMO_LINE.format(value=stored()))
if __name__ == "__main__":
main()
+43
View File
@@ -0,0 +1,43 @@
from collections.abc import Callable
from flask_day_54.domain.decorators import (
make_bold,
make_emphasis,
make_underlined,
plain_hello,
say_hello,
)
def test_make_bold_wraps_text_in_b_tags() -> None:
assert make_bold(plain_hello)() == "<b>Hello, World!</b>"
def test_make_emphasis_wraps_text_in_em_tags() -> None:
assert make_emphasis(plain_hello)() == "<em>Hello, World!</em>"
def test_make_underlined_wraps_text_in_u_tags() -> None:
assert make_underlined(plain_hello)() == "<u>Hello, World!</u>"
def test_say_hello_applies_stacked_decorators_nearest_first() -> None:
assert say_hello() == "<b><em><u>Hello, World!</u></em></b>"
def test_plain_hello_is_not_decorated() -> None:
assert plain_hello() == "Hello, World!"
def test_decorator_keeps_name_and_docstring_of_wrapped_function() -> None:
assert say_hello.__name__ == "say_hello"
assert say_hello.__doc__ == "Return the greeting."
def test_decorator_wraps_function_returning_another_string() -> None:
def goodbye() -> str:
return "Bye"
decorated: Callable[[], str] = make_bold(goodbye)
assert decorated() == "<b>Bye</b>"
+42
View File
@@ -0,0 +1,42 @@
from flask_day_54.domain import first_class_functions
from flask_day_54.domain.first_class_functions import (
add,
calculate,
outer_function,
returns_nested_function,
subtract,
)
def test_add_returns_sum_of_two_numbers() -> None:
assert add(2, 3) == 5
def test_subtract_returns_difference_of_two_numbers() -> None:
assert subtract(5, 3) == 2
def test_calculate_applies_add_when_add_is_passed() -> None:
assert calculate(2, 3, add) == 5
def test_calculate_applies_subtract_when_subtract_is_passed() -> None:
assert calculate(5, 3, subtract) == 2
def test_calculate_applies_lambda_when_lambda_is_passed() -> None:
assert calculate(4, 3, lambda n1, n2: n1 * n2) == 12
def test_outer_function_returns_nested_function_result() -> None:
assert outer_function() == "Hello from the nested function"
def test_returned_nested_function_is_callable_independently() -> None:
stored = returns_nested_function()
assert stored() == "Hello from the nested function"
def test_nested_function_is_not_a_module_attribute() -> None:
assert not hasattr(first_class_functions, "nested_function")