Want to use some more advanced features of Python in coming examples
Can now explain them in terms of what we’ve seen in previous lessons
[%inc mock_time.py %]
But this changes time.time for
everything
Want a reliable way to restore the original
If a function is just an object
We can make an object that looks like a function
[%inc callable.py %] [%inc callable.out %]
[%inc mock_object.py mark=fake %]
[%inc mock_object.py mark=fakeit %]
[%inc mock_object.py mark=test_real %]
[%inc mock_object.py mark=test_fixed %]
[% figure slug=“protocols-timeline” img=“timeline.svg” alt=“Timeline of mock operation” caption=“Timeline of mock operation.” %]
[%inc mock_object.py mark=test_record %]
[%inc mock_object.py mark=test_calc %]
A [%g protocol “protocol” %] specifies how programs can tell Python to do specific things at specific moments
__init__ to build objects
__call__ to emulate function call
Define __enter__ and __exit__ to create
a [%g context_manager “context manager” %] that a with
statement can use
[%inc ex_with.py %]
C’s constructor to create an object.__enter__ method and assign the
result to name.with block.name.__exit__() when the block finishes.__enter__ doesn’t need extra arguments
Python calls __exit__ with three values for error
handling
[%inc mock_context.py mark=contextfake %]
[%inc wrap_infinite.py %] [%inc wrap_infinite.out %]
[%inc wrap_capture.py %] [%inc wrap_capture.out %]
[%inc wrap_param.py %] [%inc wrap_param.out %]
[%inc decorator_simple.py %] [%inc decorator_simple.out %]
[%inc decorator_param.py %] [%inc decorator_param.out %]
A decorator must take exactly one argument, so how do we pass other parameters to the decorator itself?
Simple-to-learn answer would have been to treat function being
decorated like self in method definition and call
[%inc alternative_design.py %]
Python calls thing.__iter__ at the start of a
for loop to get an [%g iterator “iterator” %]
Calls iterator.__next__ repeatedly to get loop
items
Stops when the iterator raises
StopIteration
(Almost) always create a separate object so that we can run nested loops on the same target
[%inc better_iterator.py mark=buffer %]
[%inc better_iterator.py mark=cursor omit=advance %]
[%inc test_better_iterator.py mark=example %]
[% figure slug=“protocols-concept-map” img=“concept_map.svg” alt=“Concept map of reflection” caption=“Concept map.” %]