Get Started

The timer() context manager

A colleague of yours is working on a web service that processes Instagram photos. Customers are complaining that the service takes too long to identify whether or not an image has a cat in it, so your colleague has come to you for help. You decide to write a context manager that they can use to time how long their functions take to run.

This is a part of the course

“Writing Functions in Python”

View Course

Exercise instructions

  • Add a decorator from the contextlib module to the timer() function that will make it act like a context manager.
  • Send control from the timer() function to the context block.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Add a decorator that will make timer() a context manager
@contextlib.____
def timer():
  """Time the execution of a context block.

  Yields:
    None
  """
  start = time.time()
  # Send control back to the context block
  ____
  end = time.time()
  print('Elapsed: {:.2f}s'.format(end - start))

with timer():
  print('This should take approximately 0.25 seconds')
  time.sleep(0.25)

This exercise is part of the course

Writing Functions in Python

IntermediateSkill Level
4.4+
62 reviews

Learn to use best practices to write maintainable, reusable, complex functions with good documentation.

If you've ever seen the "with" keyword in Python and wondered what its deal was, then this is the chapter for you! Context managers are a convenient way to provide connections in Python and guarantee that those connections get cleaned up when you are done using them. This chapter will show you how to use context managers, as well as how to write your own.

Exercise 1: Using context managersExercise 2: The number of catsExercise 3: The speed of catsExercise 4: Writing context managersExercise 5: The timer() context manager
Exercise 6: A read-only open() context managerExercise 7: Advanced topicsExercise 8: Context manager use casesExercise 9: Scraping the NASDAQExercise 10: Changing the working directory

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free