AttributeError in "with" statement (3.2.2)

Eric Snow ericsnowcurrently at gmail.com
Wed Dec 14 14:46:58 EST 2011


On Wed, Dec 14, 2011 at 12:14 PM, Lie Ryan <lie.1296 at gmail.com> wrote:
> On 12/15/2011 03:56 AM, Eric Snow wrote:
>>
>> On Tue, Dec 13, 2011 at 11:05 PM, Eric Snow<ericsnowcurrently at gmail.com>
>>  wrote:
>>
>> If you want to be more dynamic about it you can do it, but it involves
>> black magic.  Chances are really good that being explicit through your
>> class definition is the right approach.
>
>
> Note that the black spice is to use the __class__ attribute:
>
> foo.__class__.__exit__ = foo.goodbye

Good point.  'type(foo).__exit__ ...' might be even better.
Regardless, to get the dynamicism to which Steve originally referred
(make it work when added directly to the instance), you have to use a
metaclass, which is black magic[1].  However, rarely is that sort of
thing needed, so the relatively superfluous details would likely only
cloud the question at hand.

-eric

[1] I will point out that metaclasses aren't really all that bad.
They are a tool worth understanding, even if you don't use them all
the time.  Understanding them also opens up a whole new world of
understanding how Python works, particularly regarding name lookup.



More information about the Python-list mailing list