Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A custom file class. Is this feasible?

Tags:

python

Currently I'm reading and writing binary files and am calling the struct pack/unpack functions frequently. Rather than constantly having to write something like

struct.unpack("3f", myFile.read(12))

I decided to write a function to save myself some typing, so the equivalent of the above statement in my code is

my_unpack(myFile, '3f')

Where my_unpack is defined as

struct.unpack(fmt, f.read(struct.calcsize(fmt))

But then I'm thinking what if I instead wrote things like

myFile.get_float(3)
myFile.get_char(12)
myFile.get_string(20)

It would make it a little easier to read I believe, especially since the syntax for packing and unpacking might look daunting for those that are not familiar with it.

Would this be enough reason to write my own class that inherits the File class just to provide a couple extra methods?

like image 311
MxLDevs Avatar asked Dec 04 '25 21:12

MxLDevs


1 Answers

Don't subclass. Instead, compose:

class StructReader(object):
    def __init__(self, input_file):
        self.input_file = input_file

    def get_float(self, n):
        fmt = ...
        return struct.unpack(fmt, self.input_file.read(struct.calcsize(fmt)))

    ...

When you subclass, you have to worry about namespace collisions. Composition avoids this problem.

like image 190
Jean-Paul Calderone Avatar answered Dec 06 '25 11:12

Jean-Paul Calderone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!