Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclassing file in python 3

In python 2, file was a proper class, so I wrote

class MyFile(file):  
  def floats_from_csv(self):  
    strs = self.read(1000000).split(',')  
    for i in strs:  
      yield float(i)

with MyFile("x.csv", "rt") as x:
  for i in x.floats_from_csv():
    ...

In python3 the numerous file replacements have no public constructors, so I can't subclass and get a __init__ function. I have a hack using delegation, but it's ugly. What is the approved way to create subclasses of the builtin IO classes?

like image 730
user1781661 Avatar asked Oct 28 '12 23:10

user1781661


1 Answers

What I would do is replace your subtype by a general type that supports any file-like object (if it has a read method, it’s good enough) and just encapsulate it like this.

class MyCsvHandler():
    def __init__ (self, fileObj):
        self.file = fileObj

    def floatsFromCsv (self):
        strs = self.file.read(1000000).split(',')  
        for i in strs:  
            yield float(i)

with open('x.csv', 'r') as f:
    h = MyCsvHandler(f)
    for i in h.floatsFromCsv():
        # ...

That way, you could always replace your file object by a completely different thing, for example an IO object you get from a website, or some other stream from somewhere else.

like image 61
poke Avatar answered Sep 29 '22 14:09

poke