Explaining Python’s ‘__enter__’ and ‘__exit__’

Using these magic methods (__enter__, __exit__) allows you to implement objects which can be used easily with the with statement. The idea is that it makes it easy to build code which needs some ‘cleandown’ code executed (think of it as a try-finally block). Some more explanation here. A useful example could be a database connection object (which then automagically closes … Read more

File open and close in python

The mile-high overview is this: When you leave the nested block, Python automatically calls f.close() for you. It doesn’t matter whether you leave by just falling off the bottom, or calling break/continue/return to jump out of it, or raise an exception; no matter how you leave that block. It always knows you’re leaving, so it … Read more