From 2c6571f4493e1b8b1d862e3b9eb28e5a76a9f7ae Mon Sep 17 00:00:00 2001 From: Bobby Date: Wed, 18 Nov 2020 10:02:48 -0500 Subject: [PATCH 1/2] Make this example more meaningful/fix bug (#108) By doing: ``` @contextlib.contextmanager def unlock(resource): resource = 'unlocked' ... ``` We don't really change the `resource` that is passed in. Because Python is pass by object reference, doing a re-assignment operation does not actually change the `resource` i.e. `resource = 'unlocked'` does not really work. Furthermore, the `resource` variable, with which the `unlock` function is called, is a string; strings are immutable; thus, we need to pass in a mutable data type as the `resource` to be able to demonstrate the resource's "lock state" changing. While we could have used a simple "box" tactic i.e. `resource = ['locked']`, this seemed to distract from the goal of the example. Consequently, it seemed using a small class might be clearer without detracting from the example's value. --- contextmanagers.py | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/contextmanagers.py b/contextmanagers.py index 138c6d9..021de87 100644 --- a/contextmanagers.py +++ b/contextmanagers.py @@ -12,29 +12,26 @@ @contextlib.contextmanager def unlock(resource): - resource = "unlocked" + resource.locked = False try: - yield resource + yield finally: - resource = "locked" + resource.locked = True # a resource that is locked -resource = "locked" +class Resource: + def __init__(self): + self.locked = True + +resource = Resource() # test that it is indeed locked -print(resource) +print(resource.locked) # call your 'unlock' context manager with your resource -with unlock(resource) as unlocked: - print(unlocked) # check that it is unlocked +with unlock(resource): + print(resource.locked) # check that it is unlocked # ensure it was re-locked when it left the 'unlock' context -print(resource) - - - - - - - +print(resource.locked) From cae22a0960a7bf9a39c7fb3227e283c3b86bd05b Mon Sep 17 00:00:00 2001 From: Tim Gates Date: Thu, 24 Dec 2020 23:20:23 +1100 Subject: [PATCH 2/2] docs: fix simple typo, recieves -> receives (#109) There is a small typo in metatable.py. Should read `receives` rather than `recieves`. --- metatable.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/metatable.py b/metatable.py index 040079c..caec968 100644 --- a/metatable.py +++ b/metatable.py @@ -1,5 +1,5 @@ """ -metatable with where the function recieves the dictionary and key. +metatable with where the function receives the dictionary and key. """ from collections import defaultdict