Returning a custom file object (Python 3)

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu May 28 05:29:27 EDT 2015


On 28 May 2015 at 03:16, Steven D'Aprano <steve at 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



More information about the Python-list mailing list