Manage Resources

suggest change
class File():
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        self.open_file = open(self.filename, self.mode)
        return self.open_file

    def __exit__(self, *args):
        self.open_file.close()

__init__() method sets up the object, in this case setting up the file name and mode to open file. __enter__() opens and returns the file and __exit__() just closes it.

Using these magic methods (__enter__, __exit__) allows you to implement objects which can be used easily with the with statement.

Use File class:

for _ in range(10000):
    with File('foo.txt', 'w') as f:
        f.write('foo')

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Context Managers with Statement:
* Manage Resources

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
43 Context Managers with Statement
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve