Skip to content

Instantly share code, notes, and snippets.

@GrahamDumpleton
Created November 9, 2012 02:59
Show Gist options
  • Save GrahamDumpleton/4043434 to your computer and use it in GitHub Desktop.
Save GrahamDumpleton/4043434 to your computer and use it in GitHub Desktop.
Context manager getattr test.
# Python 2.5, 2.6 runs okay.
# Python 2.7:
#
# Traceback (most recent call last):
#  File "test.py", line 33, in <module>
#    with cm2:
# AttributeError: __exit__
from __future__ import with_statement
class CM1(object):
def __enter__(self):
print '__enter__'
return self
def __exit__(self, *args):
print '__exit__'
class CM2(object):
def __init__(self, inner):
object.__setattr__(self, '_inner', inner)
def __setattr__(self, name, value):
setattr(self._inner, name, value)
def __getattr__(self, name):
return getattr(self._inner, name)
cm1 = CM1()
with cm1:
print 'CM1'
cm2 = CM2(cm1)
with cm2:
print 'CM2'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment