Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #91356
| References | <55667a6d$0$13002$c3e8da3$5496439d@news.astraweb.com> |
|---|---|
| From | Oscar Benjamin <oscar.j.benjamin@gmail.com> |
| Date | 2015-05-28 10:29 +0100 |
| Subject | Re: Returning a custom file object (Python 3) |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.122.1432805768.5151.python-list@python.org> (permalink) |
On 28 May 2015 at 03:16, Steven D'Aprano <steve@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
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Returning a custom file object (Python 3) Steven D'Aprano <steve@pearwood.info> - 2015-05-28 12:16 +1000
Re: Returning a custom file object (Python 3) Ben Finney <ben+python@benfinney.id.au> - 2015-05-28 12:40 +1000
Re: Returning a custom file object (Python 3) Marko Rauhamaa <marko@pacujo.net> - 2015-05-28 08:29 +0300
Re: Returning a custom file object (Python 3) Chris Angelico <rosuav@gmail.com> - 2015-05-28 15:49 +1000
Re: Returning a custom file object (Python 3) Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2015-05-28 17:04 +1000
Re: Returning a custom file object (Python 3) Chris Angelico <rosuav@gmail.com> - 2015-05-28 19:06 +1000
Re: Returning a custom file object (Python 3) Gary Herron <gherron@digipen.edu> - 2015-05-27 22:56 -0700
Re: Returning a custom file object (Python 3) Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2015-05-28 16:52 +1000
Re: Returning a custom file object (Python 3) Ben Finney <ben+python@benfinney.id.au> - 2015-05-28 12:34 +1000
Re: Returning a custom file object (Python 3) Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2015-05-28 10:29 +0100
csiph-web