@@ -33,6 +33,8 @@ not have the ``adafruit_`` module or package prefix.
3333
3434Both should have the CircuitPython repository topic on GitHub.
3535
36+ .. _lifetime-and-contextmanagers :
37+
3638Lifetime and ContextManagers
3739--------------------------------------------------------------------------------
3840
@@ -41,6 +43,49 @@ device requires deinitialization, then provide it through ``deinit()`` and also
4143provide ``__enter__ `` and ``__exit__ `` to create a context manager usable with
4244``with ``.
4345
46+ For example, a user can then use ``deinit()` ``::
47+
48+ import digitalio
49+ import board
50+
51+ led = digitalio.DigitalInOut(board.D13)
52+ led.direction = digitalio.DigitalInOut.Direction.OUT
53+
54+ for i in range(10):
55+ led.value = True
56+ time.sleep(0.5)
57+
58+ led.value = False
59+ time.sleep(0.5)
60+ led.deinit()
61+
62+ This will deinit the underlying hardware at the end of the program as long as no
63+ exceptions occur.
64+
65+ Alternatively, using a ``with `` statement ensures that the hardware is deinitialized::
66+
67+ import digitalio
68+ import board
69+
70+ with digitalio.DigitalInOut(board.D13) as led:
71+ led.direction = digitalio.DigitalInOut.Direction.OUT
72+
73+ for i in range(10):
74+ led.value = True
75+ time.sleep(0.5)
76+
77+ led.value = False
78+ time.sleep(0.5)
79+
80+ Python's ``with `` statement ensures that the deinit code is run regardless of
81+ whether the code within the with statement executes without exceptions.
82+
83+ For small programs like the examples this isn't a major concern because all
84+ user usable hardware is reset after programs are run or the REPL is run. However,
85+ for more complex programs that may use hardware intermittently and may also
86+ handle exceptions on their own, deinitializing the hardware using a with
87+ statement will ensure hardware isn't enabled longer than needed.
88+
4489Verify your device
4590--------------------------------------------------------------------------------
4691
0 commit comments