subclassing file objects (to extend open and close operations) in python 3 -


suppose want extend built-in file abstraction operations @ open , close time. in python 2.7 works:

class extfile(file):     def __init__(self, *args):         file.__init__(self, *args)         # stuff here      def close(self):         file.close(self)         # stuff here 

now i'm looking @ updating program python 3, in open factory function might return instance of of several different classes io module depending on how it's called. in principle subclass of them, that's tedious, , i'd have reimplement dispatching open does. (in python 3 distinction between binary , text files matters rather more in 2.x, , need both.) these objects going passed library code might them, idiom of making "file-like" duck-typed class wraps return value of open , forwards necessary methods verbose.

can suggest 3.x approach involves little additional boilerplate possible beyond 2.x code shown?

you use context manager instead. example one:

class specialfileopener:     def __init__ (self, filename, someotherparameter):         self.f = open(filename)         # more stuff         print(someotherparameter)     def __enter__ (self):         return self.f     def __exit__ (self, exc_type, exc_value, traceback):         self.f.close()         # more stuff         print('everything over.') 

then can use this:

>>> specialfileopener('c:\\test.txt', 'hello world!') f:         print(f.read())  hello world! foo bar over. 

using context block with preferred file objects (and other resources) anyway.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -