Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8730e92

Browse files
committed
Withable
1 parent a21443d commit 8730e92

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -758,6 +758,28 @@ class Counter:
758758
return self.a
759759
```
760760

761+
### Withable
762+
```python
763+
class FileReader():
764+
def __init__(self, filename):
765+
self.filename = filename
766+
def __enter__(self):
767+
self.file = open(self.filename)
768+
return self.file.read()
769+
def __exit__(self, *args):
770+
self.file.close()
771+
print(f'FileReader closed {self.filename!r}')
772+
```
773+
774+
```python
775+
>>> with open('test.txt', 'w') as file:
776+
... file.write('Hello World!')
777+
>>> with FileReader('test.txt') as text:
778+
... print(text)
779+
Hello World!
780+
FileReader closed 'test.txt'
781+
```
782+
761783
### Copy
762784
```python
763785
from copy import copy, deepcopy

0 commit comments

Comments
 (0)