Browse Source

Adds context manager demonstration along with test fil. Adds initial structure

Josh Stephens 8 months ago
commit
d73e80e57d
4 changed files with 110 additions and 0 deletions
  1. 11
    0
      Pipfile
  2. 20
    0
      Pipfile.lock
  3. 76
    0
      context_mgr_example.py
  4. 3
    0
      test.txt

+ 11
- 0
Pipfile View File

@@ -0,0 +1,11 @@
1
+[[source]]
2
+name = "pypi"
3
+url = "https://pypi.org/simple"
4
+verify_ssl = true
5
+
6
+[dev-packages]
7
+
8
+[packages]
9
+
10
+[requires]
11
+python_version = "3.7"

+ 20
- 0
Pipfile.lock View File

@@ -0,0 +1,20 @@
1
+{
2
+    "_meta": {
3
+        "hash": {
4
+            "sha256": "7e7ef69da7248742e869378f8421880cf8f0017f96d94d086813baa518a65489"
5
+        },
6
+        "pipfile-spec": 6,
7
+        "requires": {
8
+            "python_version": "3.7"
9
+        },
10
+        "sources": [
11
+            {
12
+                "name": "pypi",
13
+                "url": "https://pypi.org/simple",
14
+                "verify_ssl": true
15
+            }
16
+        ]
17
+    },
18
+    "default": {},
19
+    "develop": {}
20
+}

+ 76
- 0
context_mgr_example.py View File

@@ -0,0 +1,76 @@
1
+
2
+from typing import IO, Callable
3
+from contextlib import contextmanager
4
+
5
+class FileHandler:
6
+    """Demonstrates how to build a class to be used as a context manager"""
7
+    def __init__(self, file_path: str):
8
+        self.file_path = file_path
9
+        self.file_handler = None
10
+    
11
+    def __enter__(self) -> IO:
12
+        """Context Manager begins the work here"""
13
+        self.file_handler = open(self.file_path)
14
+        return self.file_handler
15
+    
16
+    def __exit__(self, *exec: Callable):
17
+        """Context Manager has comnpleted and time to clean up"""
18
+        self.file_handler.close()
19
+
20
+
21
+@contextmanager
22
+def text_file(file_path: str) -> IO:
23
+    """Demonstrates a function as a context manager"""
24
+    file = open(file_path)
25
+    try:
26
+        yield file
27
+    except:
28
+        file.close()
29
+        raise
30
+    else:
31
+        file.close()
32
+
33
+if __name__ == '__main__':
34
+    print('*' * 100)
35
+    print("Using Try Finally to demonstrate how a context manager behaves when implemented")
36
+    print('*' * 100)
37
+    # Long way to write a context manager
38
+    try:
39
+        file = open('test.txt')
40
+
41
+        for line in file.readlines():
42
+            print(line.rstrip())
43
+    finally:
44
+        file.close()
45
+    
46
+    print()
47
+    
48
+    print('*' * 100)
49
+    print("Normal open function")
50
+    print('*' * 100)
51
+    # Standard way of using a context manager
52
+    with open('test.txt') as infile:
53
+        for line in infile.readlines():
54
+            print(line.rstrip())
55
+    
56
+    print()
57
+
58
+    print('*' * 100)
59
+    print("Class Context Manager")
60
+    print('*' * 100)
61
+    # Class As a File Handler written to be a context manager. 
62
+    with FileHandler('test.txt') as infile:
63
+        for line in infile.readlines():
64
+            print(line.rstrip())
65
+
66
+    print()
67
+
68
+    print('*' * 100)
69
+    print("Function Context Manager")
70
+    print('*' * 100)
71
+    # Function that is written to be a context manager.
72
+    with text_file('test.txt') as infile:
73
+        for line in infile.readlines():
74
+            print(line.rstrip())
75
+
76
+    print()

+ 3
- 0
test.txt View File

@@ -0,0 +1,3 @@
1
+Hello World!!
2
+I am just a normal text file.
3
+Nothing to see here.

Loading…
Cancel
Save