Main Content

Setting up and tearing down with the Python with keyword

Archive - Originally posted on "The Horse's Mouth" - 2015-10-16 06:51:20 - Graham Ellis

Python's with operator lets you set up and tear down an object for use in a bock of code - typically useful for a file handle / resource accessor. Here's an example of it in use:

  with day() as today:
    print ("Today it is " + today)


It's set up using the __enter__ method for the object, and released / torn down using the __exit__ method. Here's the setting up of my "day" class for this example:

  class day:
    def __enter__(self):
      daymeal = ("Beef Salad","Curried Beef","Sausages","Pasties","Fish","Sandwiches","Roast Beef")
      self.food = daymeal[datetime.datetime.today().weekday()]
      print ("serving " + self.food)
      return self.food.upper()
    def __exit__(self ,type, value, traceback):
      print ("cleaning up from eating " + self.food)


Python's in operator when used with an if lets you check whether any value in a collection (list or tuple) is equal to the gieven value - i.e. check if a value's in a list, and with the use of a not you can check if a value's missing (not present):

  stuff = [20,"fifty",70,66]
  if 55 in stuff: print (1)
  if not 55 in stuff: print (3)


Python's in operator when used with a for iterates through a collection - placing a refernce to each item in the collection in turn into a target variable so that you can step through them in a loop:

  for value in stuff:
    print ("Value is {}".format(value))


Complete program showing all of these: [here].

Sample output:

  WomanWithCat:flask grahamellis$ python3 shin
  2
  3
  serving Fish
  Today it is FISH
  cleaning up from eating Fish
  None
  None
  None
  Value is 20
  Value is fifty
  Value is 70
  Value is 66
  WomanWithCat:flask grahamellis$


Next Python courses start on 15th December, and further courses follow every 2 months next year. See [here] for a full schedule. "Learning to program in Python" is for newcomers to programming; "Python Programming" for those with prior experience in another language.