python - Automatic selection of file handler depending on file extension -
this how see it:
class basehandler: def open(self): pass def close(self): pass class txthandler(basehandler): def open(self): pass def close(self): pass class xmlhandler(basehandler): def open(self): pass def close(self): pass def open_file(file_path): handler = basehandler(file_path)
for example, if file_path '..\file.xml' must return xmlhandler. please tell me, need implement functionality?
i know can implement via if-elif-else statement, i'm trying avoid dozen elif.
this preferred pythonic way:
import os handlers = {'.xml': xmlhandler, '.txt': txthandler} def open_file(file_path): ext = os.path.splitext(file_path)[1] handler = handlers.get(ext, basehandler)
in above code associate handlers extensions using dictionary.
in open_file
function extract extension , use handler dictionary, considering case key doesn't exist.
i so:
if ext in handlers: handler = handlers[ext] else: handler = basehandler
but of course using get
method of dictionary nicer!
Comments
Post a Comment