Python Forum
Whats a good design/approach? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Whats a good design/approach? (/thread-21129.html)



Whats a good design/approach? - hshivaraj - Sep-15-2019

Hi all.

I have this simple code, which does pretty simple things as open a file within the class. But i cant decide what the best design. Is approach1 is better approach2? I need to understand when re-raise an exception and also is it better to catch FileNotFoundError in the class or in the main. What the best approach?

import json
import sys

class Approach2FileNotFoundException(Exception):
    pass


class Approach1:

    def __init__(self, config):
        self.config = self._open(config)

    def _open(self, config):
        with open(config, "r") as fh:
            return json.load(fh)


class Approach2:

    def __init__(self, config):
        self.config = self._open(config)

    def _open(self, config):
        try:
            with open(config, "r") as fh:
                return json.load(fh)
        except FileNotFoundError as err:
            raise Approach2FileNotFoundException(err)


def main():
    try:
        a1 = Approach1("./config.txt")
    except FileNotFoundError as err:
        print(err)
        sys.exit(1)

    try:
        a2 = Approach2("./config.txt")
    except Approach2FileNotFoundException as err:
        print(err)
        sys.exit(1)


if __name__ == "__main__":
    main()
Many thanks


RE: Whats a good design/approach? - snippsat - Sep-16-2019

(Sep-15-2019, 10:11 PM)hshivaraj Wrote: Is approach1 is better approach 2
Both work in this case,approach 2 you can modify the error message.
It's not unclear what happen here in the case without try,except.
def _open(config):
    with open(config, "r") as fh:
        return fh.read()
>>> _open('foo.txt')
'hello'

>>> _open('foo999.txt')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "file_try.py", line 3, in _open
    with open(config, "r") as fh:
FileNotFoundError: [Errno 2] No such file or directory: 'foo999.txt'

[Errno 2] No such file or directory: 'foo999.txt'
Shorter just print the error from last line over.
def _open(config):
    try:
        with open(config, "r") as fh:
            return fh.read()
    except OSError as err:
        print(err)
>>> _open('foo.txt')
'hello'

>>> _open('foo999.txt')
[Errno 2] No such file or directory: 'foo999.txt'