Python context manager that measures time
Question: 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.

    
    
    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
    

This code leaves `t=1` 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.

[PEP 343 describes](https://www.python.org/dev/peps/pep-0343/) in more detail
how contect manager works but I do not understand most of it.


Answer: You can't get that to assign your timing to `t`. As described in the PEP, the
variable you specify in the `as` clause (if any) gets assigned the result of
calling `__enter__`, not `__exit__`. In other words, `t` is only assigned at
the _start_ of the `with` block, not at the end.

What you could do is change your `__exit__` so that instead of returning the
value, it does `self.t = time.clock() - self.t`. Then, after the `with` block
finishes, the `t` attribute of the context manager will hold the elapsed time.

To make that work, you also want to return `self` instead of `1` from
`__enter__`. Not sure what you were trying to achieve by using `1`.

So it looks like this:

    
    
    class catchtime(object):
        def __enter__(self):
            self.t = time.clock()
            return self
    
        def __exit__(self, type, value, traceback):
            self.t = time.clock() - self.t
    
    with catchtime() as t:
        time.sleep(1)
    
    print(t.t)
    

And a value pretty close to 1 is printed.

