AttributeError in "with" statement (3.2.2)
Terry Reedy
tjreedy at udel.edu
Wed Dec 14 01:29:13 EST 2011
On 12/14/2011 1:05 AM, Eric Snow wrote:
> On Tue, Dec 13, 2011 at 10:42 PM, Steve Howell<showell30 at yahoo.com> wrote:
>> I'm using Python 3.2.2, and the following program gives me an error
>> that I don't understand:
>>
>> class Foo:
>> pass
>>
>> foo = Foo()
>> foo.name = "Steve"
>>
>> def add_goodbye_function(obj):
>> def goodbye():
>> print("goodbye " + obj.name)
>> obj.goodbye = goodbye
>>
>> add_goodbye_function(foo)
>> foo.goodbye() # outputs goodbye Steve
>> foo.__exit__ = foo.goodbye
>> foo.__exit__() # outputs goodbye Steve
foo.goodbye, aliased as foo.__exit__, is a *function* attribute of the
foo *instance*.
>> with foo: # fails with AttributeError: __exit__
>> print("doing stuff")
>>
>> I am dynamically adding an attribute __exit__ to the variable foo,
>> which works fine when I call it directly, but it fails when I try to
>> use foo as the expression in the with statement. Here is the full
>> output:
>>
>>> python3 with.coffee
>> goodbye Steve
>> goodbye Steve
>> Traceback (most recent call last):
>> File "with.coffee", line 17, in<module>
>> with foo: # fails with AttributeError:
>> AttributeError: __exit__
>>
>> What am I doing wrong?
To complement what Eric says below: The with statement is looking for an
instance *method*, which by definition, is a function attribute of a
*class* (the class of the context manager) that takes an instance of the
class as its first parameter. Notice that goodbye does not take any
parameter. The first parameter is conventionally called 'self', but that
is not a requirement. That it be there, that it expect to be bound to an
instance, and that the function be bound to the class are requirements.
> That is a tricky one.
>
> As with many of the special methods (start and end with __) in Python,
> the underlying mechanism in the interpreter is directly pulling the
> function from the class object. It does not look to the instance
> object for the function at any time. See
> http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes.
--
Terry Jan Reedy
More information about the Python-list
mailing list