The following code is an example of the book, <Fluent Python> to explain the ContextManager of Python.
class LookingGlass:
def __enter__(self):
import sys <----- HERE
self.original_write = sys.stdout.write
sys.stdout.write = self.reverse_write
return 'JABBERWOCKY'
def reverse_write(self, text):
self.original_write(text[::-1])
def __exit__(self, exc_type, exc_value, traceback):
import sys <---- HERE
sys.stdout.write = self.original_write
if exc_type is ZeroDivisionError:
print('Please DO NOT divide by zero!')
return True
There are two import sys
statements. Why didn't they put code before the class declaration?
I moved the code and tested. However I didn't find the difference.