0

My question relates mostly to how you use the with keyword in a class in Python.

If you have a Class which contains a file object, how do you use the with statement, if at all.

For example, I don't use with here:

class CSVLogger:
    def __init__(self, rec_queue, filename):
        self.rec_queue = rec_queue
        ## Filename specifications
        self.__file_string__ = filename
        f = open(self.__file_string__, 'wb')
        self.csv_writer = csv.writer(f,  newline='', lineterminator='\n', dialect='excel')

If I then do things to the file in another method, For example:

    def write_something(self, msg):
        self.csv_writer(msg)

Is this suitable? Should I include the with somewhere? I'm just afraid that one the __init__ exits, the with exits and might close the file?

jnd
  • 754
  • 9
  • 20
  • http://stackoverflow.com/a/27574601/742269 – Avión Jul 01 '15 at 09:12
  • Never give your own attributes or methods double-underscores on both sides. Those names are intended for Python's own attributes, which you may override, but not define your own. – Daniel Roseman Jul 01 '15 at 09:13

1 Answers1

1

Yes, you are correct with automatically closes the file when its scope ends, so if you use with statement in your __init__() function, the write_something function would not work.

Maybe you can use the with statement in the main part of the program, and instead of opening the file in __init__() function you can pass in the file object as a parameter to the __init__() function. and then do all operations you would like to do in the file within the with block.

Example -

Class would look like -

class CSVLogger:
    def __init__(self, rec_queue, filename, f):
        self.rec_queue = rec_queue
        ## Filename specifications
        self.__file_string__ = filename
        self.csv_writer = csv.writer(f,  newline='', lineterminator='\n', dialect='excel')
    def write_something(self, msg):
        self.csv_writer(msg)

The main program may look like -

with open('filename','wb') as f:
    cinstance = CSVLogger(...,f) #file and other parameters
    .... #other logic
    cinstance.write_something("some message")
    ..... #other logic

Though if this complicates thing a-lot, you are better off not using the with statement and rather making sure that you close the file when when its need is over.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176