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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With