On 28 May 2015 at 03:16, Steven D'Aprano <st...@pearwood.info> wrote: > I'd like to return a custom file object, say my own subclass. I can easily > subclass the file object: > > > from io import TextIOWrapper > class MyFile(TextIOWrapper): > pass > > > but how do I tell open() to use MyFile?
Does the below do what you want? #!/usr/bin/env python3 class Wrapper: def __init__(self, wrapped): self._wrapped = wrapped def __getattr__(self, attrname): return getattr(self._wrapped, attrname) # Special methods are not resolved by __getattr__ def __iter__(self): return self._wrapped.__iter__() def __enter__(self): return self._wrapped.__enter__() def __exit__(self, *args): return self._wrapped.__exit__(*args) class WrapFile(Wrapper): def write(self): return "Writing..." f = WrapFile(open('wrap.py')) print(f.readline()) with f: print(len(list(f))) print(f.write()) > > Answers for Python 3, thanks. Tested on 3.2. -- Oscar -- https://mail.python.org/mailman/listinfo/python-list