0

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.

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
cybaek
  • 865
  • 1
  • 8
  • 10
  • 1
    I'd say they should be "on the first line" (that is, outside the class). – BrenBarn Feb 25 '17 at 05:31
  • 1
    I might be wrong on this, but it doesn't change what the code does, it's a style of programming where the imports happen right where they are used, so you can keep track of which imports each method uses instead of having a big list of imports at the top of the file and not having any easy way to see where they are used - and so they don't get imported all at once, only if/when the method is called. – TessellatingHeckler Feb 25 '17 at 05:37

0 Answers0