Python Forum
Whats a good design/approach?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Whats a good design/approach?
#2
(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'
Reply


Messages In This Thread
Whats a good design/approach? - by hshivaraj - Sep-15-2019, 10:11 PM
RE: Whats a good design/approach? - by snippsat - Sep-16-2019, 01:44 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Advice needed on how to approach this problem... sawtooth500 1 392 Apr-06-2024, 01:55 PM
Last Post: snippsat
  Good class design - with a Snake game as an example bear 1 2,015 Jan-24-2024, 08:36 AM
Last Post: annakenna
  Sound Approach for Running a Shell Command? matt_the_hall 8 3,625 Dec-14-2020, 02:52 PM
Last Post: matt_the_hall
  Whats wrong with the elif? inunanimous93 3 2,637 Nov-30-2020, 03:58 AM
Last Post: deanhystad
  Need feedback on my approach for python dashboard for Asana pashtett 0 1,410 Nov-24-2020, 11:51 AM
Last Post: pashtett
  Whats Wrong!? rjay81 3 2,397 May-13-2020, 08:02 PM
Last Post: rjay81
  Can u see this code and tell whats wrong with it? AhmadKamal 14 5,777 Apr-29-2020, 11:09 AM
Last Post: jefsummers
  Approach to creating Audit table pynewbie 4 4,079 Feb-24-2020, 06:12 PM
Last Post: pynewbie
  list approach due nested order 3Pinter 6 3,022 Oct-07-2019, 01:49 PM
Last Post: 3Pinter
  elevator simulator...whats the wrong at this code? tasos710 5 6,093 Jun-11-2019, 01:38 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020