title: Python context manager that measures time
body: <p>I am struggling to make a piece of code that allows to measure time spent within a "with" statement and assigns the time measured (a float) to the variable provided in the "with" statement.</p>
  
  <pre><code>import time
  
  class catchtime:
      def __enter__(self):
          self.t = time.clock()
          return 1
  
      def __exit__(self, type, value, traceback):
          return time.clock() - self.t
  
  with catchtime() as t:
      pass
  </code></pre>
  
  <p>This code leaves <code>t=1</code> and not the difference between clock() calls. How to approach this problem? I need a way to assign a new value from within the exit method.</p>
  
  <p><a href="https://www.python.org/dev/peps/pep-0343/" rel="noreferrer">PEP 343 describes</a> in more detail how contect manager works but I do not understand most of it.</p>