Anonymous Functions: lambda
- anonymous function expressed as a single statement.
Syntax (?)
lambda argument1, argument2 : expression
def edit_story(words, func):
for word in words:
print(func(word))
stairs = ['thud', 'meow', 'thud', 'hiss']
def enliven(word):
return word.capitalized() + '!'
edit_story(stairs, enliven)
# lambda version
edit_story(stairs, lambda word: word.capitalized() + '!')
Testing Logic
Ensure your tests cover various scenarios:
Empty list:
- What happens when words is empty? No function:
- How does the function behave if func is missing or invalid?
pytesting
import pytest
def edit_story(words, func):
for word in words:
print(func(word))
stairs = ['thud', 'meow', 'thud', 'hiss']
def enliven(word):
return word.capitalize() + '!'
def test_edit_story_with_function():
# Arrange
expected_output = ['Thud!', 'Meow!', 'Thud!', 'Hiss!']
# Act
edit_story(stairs.copy(), enliven) # Don't modify original list
# Assert - This part needs to be adjusted, as edit_story prints but doesn't return anything.
# Use a mock or capture output to assert the printed values.
def test_edit_story_with_lambda():
# Arrange
expected_output = ['Thud!', 'Meow!', 'Thud!', 'Hiss!']
# Act
edit_story(stairs.copy(), lambda word: word.capitalize() + '!') # Don't modify orig_list
# Assert - Similarly, need to handle the printed output here.
import pytest
from unittest.mock import patch
def edit_story(words, func):
for word in words:
print(func(word))
stairs = ['thud', 'meow', 'thud', 'hiss']
def enliven(word):
return word.capitalize() + '!'
@patch('__main__.print')
def test_edit_story_with_function(mock_print):
# Arrange
expected_output = ['Thud!', 'Meow!', 'Thud!', 'Hiss!']
# Act
edit_story(stairs.copy(), enliven)
# Assert
mock_print.assert_has_calls([pytest.approx(call(output)) for output in expected_output])
# Similar test with lambda, using mock_print.assert_has_calls()
x = lambda a, b: a * b
print(x(5, 6))
# OUTPUT
30
"""doubles the number you send in"""
1 def myfunc(n):
2 return lambda a : a * n
3
4 mydoubler = myfunc(2)
5
6 print(mydoubler(11))