Py3K: file inheritance

Y

Yosifov Pavel

In the Python 2.x was simple to create own file object:

class MyFile(file):
pass

for example to reimplement write() or something else. How to do it in
Python 3.x?
 
I

Ian Kelly

In the Python 2.x was simple to create own file object:

class MyFile(file):
špass

for example to reimplement write() or something else. How to do it in
Python 3.x?

See the docs for the io module. Depending on what you want to do, you
probably need to subclass either io.FileIO or io.TextIOWrapper.
 
Y

Yosifov Pavel

See the docs for the io module.  Depending on what you want to do, you
probably need to subclass either io.FileIO or io.TextIOWrapper.

Little silly example:

class MyFile(file):
def __init__(self, *a, **ka):
super(MyFile, self).__init__(*a, **ka)
self.commented = 0
def write(self, s):
if s.startswith("#"):
self.commented += 1
super(MyFile, self).write(s)

When I tried in Python 3.x to inherit FileIO or TextIOWrapper and then
to use MyFile (ex., open(name, mode, encoding), write(s)...) I get
errors like 'unsupported write' or AttributeError 'readable'... Can
you show me similar simple example like above but in Python 3.x?
 
I

Ian Kelly

Little silly example:

class MyFile(file):
šdef __init__(self, *a, **ka):
š šsuper(MyFile, self).__init__(*a, **ka)
š šself.commented = 0
šdef write(self, s):
š šif s.startswith("#"):
š š šself.commented += 1
š š šsuper(MyFile, self).write(s)

When I tried in Python 3.x to inherit FileIO or TextIOWrapper and then
to use MyFile (ex., open(name, mode, encoding), write(s)...) I get
errors like 'unsupported write' or AttributeError 'readable'... Can
you show me similar simple example like above but in Python 3.x?

class MyTextIO(io.TextIOWrapper):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.commented = 0
def write(self, s):
if s.startswith('#'):
self.commented += 1
super().write(s)

buffered = open(name, 'wb')
textio = MyTextIO(buffered, encoding='utf-8')
textio.write('line 1')
textio.write('# line 2')
textio.close()
print(textio.commented)

HTH,
Ian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,158
Messages
2,570,881
Members
47,414
Latest member
djangoframe

Latest Threads

Top