>>> def show(opened): ... with opened as file: ... for line in file: ... print line.strip() ...
>>> show(open("test.txt")) blah1 blah2 blah3 # # Good! I wonder if I can do that with StringIO ... # >>> import StringIO >>> show(StringIO.StringIO("blah1\nblah2\nblah3\n")) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in show AttributeError: StringIO instance has no attribute '__exit__' # # Oh dear ... I'll need to proxy it ... # >>> class IterNoGuardProxy(object): ... def __init__(self, t): ... self.t = t ... def __enter__(self): ... return self ... def __exit__(self, type, value, traceback): ... return False ... def __iter__(self): ... return self.t.__iter__() ... >>> show(IterNoGuardProxy(StringIO.StringIO("blah1\nblah2\nblah3\n"))) blah1 blah2 blah3 >>> # # Great! That works well. Now I wonder if I can do it generically # in a way that can proxy for ALL methods (including, but not limited to, __iter__) # >>> class NoGuardProxy(object): ... def __init__(self, t): ... self.t = t ... def __enter__(self): ... return self ... def __exit__(self, type, value, traceback): ... return False ... def __getattr__(self): ... return self.t.__getattr__(self) ... >>> show(NoGuardProxy(StringIO.StringIO("blah1\nblah2\nblah3\n"))) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in show TypeError: 'NoGuardProxy' object is not iterable # # Now I'm stuck. # Can anyone help? # -- http://mail.python.org/mailman/listinfo/python-list