Main Content

with in Python - examples of use, and of defining your own context

Archive - Originally posted on "The Horse's Mouth" - 2016-11-02 01:12:45 - Graham Ellis

The with keyword in Python lets you set up an object with a block scope and a defined closure. It's implemented in the standard file handle object library - see example at [here] and you can implement it for your own object using the __enter__ and __exit__ methods - example [here]. Note that the __exit__ method differs from the usual descructor in that you get to choose via your scope the point at which you release the data within your object, and (alas) the object isn't actuall destroyed in that the name does not go out of scope.

 class trackorder(object):
         def __init__(self,top):
                 self.values = range(1,top+1)
         def __enter__(self):
                 return self
         def __exit__(self,a,b,c):
                 self.values = []
 
 # Big list in "trax" while it's used
 
 with trackorder(7) as trax:
         print(trax)
         for t in trax.values:
                 print(t)
         print("Length within block: " + str(len(trax.values)))
 
 # gone away outside the "with" area
 
 print("Length outside block: " + str(len(trax.values)))


Inside the block, the length reports a 7 element long list held in the trackorder object; upon exit from the block, this has been reduced to a list of zero length, though the name and object still exist.