Context manager with class methods

Mel mwilson at the-wire.com
Thu Sep 22 08:45:18 EDT 2011


Gavin Panella wrote:

> Hi,
> 
> On Python 2.6 and 3.1 the following code works fine:
> 
>     class Foo(object):
>     
>         @classmethod
>         def __enter__(cls):
>             print("__enter__")
>     
>         @classmethod
>         def __exit__(cls, exc_type, exc_value, traceback):
>             print("__exit__")
>     
>     with Foo: pass
> 
> However, in 2.7 and 3.2 I get:
> 
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in <module>
>     AttributeError: __exit__
> 
> Is this a regression or a deliberate change? Off the top of my head I
> can't think that this pattern is particularly useful, but it seems
> like something that ought to work.

This seems to work:



class MetaWith (type):
    @classmethod
    def __enter__(cls):
        print("__enter__")

    @classmethod
    def __exit__(cls, exc_type, exc_value, traceback):
        print("__exit__")

class With (object):
    __metaclass__ = MetaWith
    
with With:
    pass
    


	Mel.	




More information about the Python-list mailing list