Title: "with" statement error message is more confusing in Py2.7
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 2.7
Status: closed Resolution: out of date
Dependencies: Superseder:
Assigned To: Nosy List: Ismael.Garrido, benjamin.peterson, eric.araujo, zach.ware
Priority: low Keywords:

Created on 2011-07-06 03:58 by Ismael.Garrido, last changed 2020-04-26 16:27 by zach.ware. This issue is now closed.

Messages (4)
msg139918 - (view) Author: Ismael Garrido (Ismael.Garrido) Date: 2011-07-06 03:58
Using the "with" statement wrongly results in a confusing error message.

Code (originally written by Alex Gaynor):

class Timer(object):
    def __enter__(self):
        self.start = time.time()
    def __exit__(self, exc_type, exc_val, tb):
        print "Section time: ", time.time() - self.start

#Note the error here, I call the class, not an instance
with Timer:


Compare the Python 2.6 error:

ismael@chaos:~/Escritorio$ python 
Traceback (most recent call last):
  File "", line 8, in <module>
    with Timer:
TypeError: unbound method __enter__() must be called with Timer instance as first argument (got nothing instead)

Against Python 2.7:

ismael@chaos:~/Escritorio$ python2.7 
Traceback (most recent call last):
  File "", line 8, in <module>
    with Timer:
AttributeError: __exit__
msg139946 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2011-07-06 19:23
The message is not inaccurate, but indeed misleading. In wonder what to do considering the traditional message of AttributeError is simply the missing attribute.
msg140026 - (view) Author: √Čric Araujo (eric.araujo) * (Python committer) Date: 2011-07-08 13:55
Could AttributeError be improved to say something like this:

AttributeError: type 'type' has no attribute '__enter__'
msg367311 - (view) Author: Zachary Ware (zach.ware) * (Python committer) Date: 2020-04-26 16:27
As 2.7 has reached end-of-life, I'm closing the issue.
Date User Action Args
2020-04-26 16:27:46zach.waresetstatus: open -> closed

nosy: + zach.ware
messages: + msg367311

resolution: out of date
stage: resolved
2011-07-08 13:55:37eric.araujosetnosy: + eric.araujo
messages: + msg140026
2011-07-06 19:23:07benjamin.petersonsetpriority: normal -> low
nosy: + benjamin.peterson
messages: + msg139946

2011-07-06 03:58:02Ismael.Garridocreate