0

This is how I 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 is '..\file.xml' it must return XMLHandler. Could anyone please tell me, what I need to do to implement this functionality?

I know I can implement this via if-elif-else statement, but I'm trying to avoid a dozen elif.

aiscy
  • 113
  • 2
  • 12

2 Answers2

2

This is my 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 the above code I associate handlers with extensions using a dictionary.

In the open_file function I extract the extension and use it to get the handler from the dictionary, with considering the case where the key doesn't exist.

I could also do it like so:

if ext in handlers:
    handler = handlers[ext]
else:
    handler = BaseHandler

But of course using the get method of the dictionary is nicer!

Israel Unterman
  • 13,158
  • 4
  • 28
  • 35
1

You could depending on the filetype, for example by checking the extension like here: Checking file extension choose an appropriate handler class.

Something along those lines:

def open_file(file_path):
    if file_path.lower().endswith('.txt'):
        handler = TxtHandler(file_path)
    elif file_path.lower().endswith('.xml'):
        handler = XMLHandler(file_path)
    else:
        handler = BaseHandler(file_path) #or error
Community
  • 1
  • 1
snow
  • 438
  • 3
  • 7
  • Thank you for prompt reply. I know I can implement this via if-elif-else statement, but I'm trying to avoid a dozen elif. – aiscy Jan 20 '17 at 09:07