Deutsch English Français Italiano |
<mailman.24.1720481658.2981.python-list@python.org> View for Bookmarking (what is this?) Look up another Usenet article |
Path: ...!fu-berlin.de!uni-berlin.de!not-for-mail From: Rob Cliffe <rob.cliffe@btinternet.com> Newsgroups: comp.lang.python Subject: Re: Best use of "open" context manager Date: Sat, 6 Jul 2024 14:27:52 +0100 Lines: 74 Message-ID: <mailman.24.1720481658.2981.python-list@python.org> References: <954c4ca8-cf37-4482-a1be-46d39cb503f9@btinternet.com> <CAHVvXxSKiws7R9v_3z9_8TP-Zsbw9MaXsNKxThLP4odWAcTUCA@mail.gmail.com> <74a41289-d62f-465f-a5ac-665843c03528@btinternet.com> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Trace: news.uni-berlin.de DDIyM+qTUrMJIMuQDv7nRQ14NRgW+U3Rq4uPcc6Fhdbw== Cancel-Lock: sha1:kZY10C7uJcumtowtCFjtmP43cqY= sha256:w/hKyQsM+5EByYMS0iDzW8VpQdITrPDKl/frQU2SVOs= Return-Path: <rob.cliffe@btinternet.com> X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org Authentication-Results: mail.python.org; dkim=pass reason="2048-bit key; unprotected key" header.d=btinternet.com header.i=@btinternet.com header.b=re+vW8oH; dkim-adsp=pass; dkim-atps=neutral X-Spam-Status: OK 0.006 X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'this:': 0.03; '(which': 0.04; 'jul': 0.04; '(e.g.': 0.05; 'improvement': 0.05; '"python': 0.07; 'e.g.': 0.07; 'action,': 0.09; 'enough.': 0.09; 'situations': 0.09; '(even': 0.16; '2024': 0.16; 'answer.': 0.16; 'applies': 0.16; 'colon': 0.16; 'decreases': 0.16; 'exception.': 0.16; 'filename': 0.16; 'frequently': 0.16; 'instead.': 0.16; 'intention': 0.16; 'readability': 0.16; 'targeted': 0.16; 'wrote:': 0.16; 'larger': 0.17; 'code.': 0.17; 'bug': 0.19; 'to:addr:python-list': 0.20; "i've": 0.22; 'exception': 0.22; 'ran': 0.22; 'sat,': 0.22; 'code': 0.23; 'lines': 0.23; 'local': 0.27; 'function': 0.27; 'wrong': 0.28; 'error': 0.29; 'header :User-Agent:1': 0.30; 'raise': 0.31; 'think': 0.32; 'fine.': 0.32; 'point,': 0.32; 'python-list': 0.32; "wouldn't": 0.32; 'received:192.168.1': 0.32; 'but': 0.32; 'there': 0.33; 'particular': 0.33; 'header:In-Reply-To:1': 0.34; 'class': 0.37; 'received:192.168': 0.37; 'file': 0.38; 'way': 0.38; 'could': 0.38; 'thanks': 0.38; 'least': 0.39; 'text': 0.39; 'handle': 0.39; 'use': 0.39; 'block': 0.39; 'program.': 0.40; 'received:213': 0.40; 'something': 0.40; 'want': 0.40; 'try': 0.40; 'should': 0.40; 'kept': 0.61; 'skip:o 10': 0.61; 'here': 0.62; 'clear': 0.64; 'mainly': 0.64; 'your': 0.64; 'dedicated': 0.65; 'bad': 0.67; 'small,': 0.69; 'raised': 0.70; 'suite': 0.71; 'catch': 0.84; 'catching': 0.84; 'exceptions': 0.84; 'oscar': 0.84; 'readability.': 0.84; 'rob': 0.84; 'subject:manager': 0.84; 'subject:open': 0.84; 'violates': 0.84; 'you.\xc2\xa0': 0.84; 'worry': 0.95 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=btinternet.com; s=btmx201904; t=1720272473; bh=3Rz36ClkKUwXNuy1eZHIxekh5wM8rUxZwiKVn9pTZT8=; h=Message-ID:Date:MIME-Version:Subject:To:References:From:In-Reply-To; b=re+vW8oH+NiMdgCClHipasobNjSbArzMHlvzOjJJuLlmcTX8wIyrTtxSgco6jrnQKnowBxW7lqCZh3p5s+5+nMqy219CpfDHncd8QqSCqGZz2ANuqRnn/Jvu0275Xyvo+0tfs15GNRPcjuB7yQZ8zKOHGBcHTBwQdB0PphPXVFMxhL2OiGSG4NlFIVZwpnUbbS+/RAItHzOV59Ds3Ml6bUNeRp482k/ywFkE7J8QP4L7YrmQ0RO/I2pKKz/FfEbnQMGnZ7U5IQOSywd3aoVaF4RQB0fvW04UOaWPGyF6kLM4ljq3Bfh0fB/GzGjLFjO+Nt1chsOFD4AQrMO4nZHtiQ== Authentication-Results: btinternet.com; auth=pass (PLAIN) smtp.auth=rob.cliffe@btinternet.com; bimi=skipped X-SNCR-Rigid: 6577B465169C820C X-Originating-IP: [86.139.197.7] X-OWM-Source-IP: 86.139.197.7 X-OWM-Env-Sender: rob.cliffe@btinternet.com X-VadeSecure-score: verdict=clean score=0/300, class=clean X-RazorGate-Vade: gggruggvucftvghtrhhoucdtuddrgeeftddrvdefgdeihecutefuodetggdotefrodftvfcurfhrohhfihhlvgemuceutffkvffkuffjvffgnffgvefqofdpqfgfvfenuceurghilhhouhhtmecufedtudenucenucfjughrpefkffggfgfuvfhfhfgjtgfgsehtkeertddtvdejnecuhfhrohhmpeftohgsucevlhhifhhfvgcuoehrohgsrdgtlhhifhhfvgessghtihhnthgvrhhnvghtrdgtohhmqeenucggtffrrghtthgvrhhnpeetteeuffetffegteffheevheejudffkeelteduveekteekheetvedujeegkeehveenucfkphepkeeirddufeelrdduleejrdejnecuvehluhhsthgvrhfuihiivgeptdenucfrrghrrghmpehhvghloheplgduledvrdduieekrddurddvtdekngdpihhnvghtpeekiedrudefledrudeljedrjedpmhgrihhlfhhrohhmpehrohgsrdgtlhhifhhfvgessghtihhnthgvrhhnvghtrdgtohhmpdhnsggprhgtphhtthhopedupdhrtghpthhtohepphihthhhohhnqdhlihhsthesphihthhhohhnrdhorhhgpdhrvghvkffrpehhohhsthekiedqudefledqudeljedqjedrrhgrnhhgvgekiedqudefledrsghttggvnhhtrhgrlhhplhhushdrtghomhdprghuthhhpghushgvrheprhhosgdrtghlihhffhgvsegsthhinhhtvghrnhgvthdrtghomhdpghgvohfkrfepifeupdfovfetjfhoshhtpehrvgdqphhrugdqrhhgohhuthdqtddtud X-RazorGate-Vade-Verdict: clean 0 X-RazorGate-Vade-Classification: clean X-SNCR-hdrdom: btinternet.com User-Agent: Mozilla Thunderbird Content-Language: en-GB In-Reply-To: <CAHVvXxSKiws7R9v_3z9_8TP-Zsbw9MaXsNKxThLP4odWAcTUCA@mail.gmail.com> X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.39 Precedence: list List-Id: General discussion list for the Python programming language <python-list.python.org> List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe> List-Archive: <https://mail.python.org/pipermail/python-list/> List-Post: <mailto:python-list@python.org> List-Help: <mailto:python-list-request@python.org?subject=help> List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe> X-Mailman-Original-Message-ID: <74a41289-d62f-465f-a5ac-665843c03528@btinternet.com> X-Mailman-Original-References: <954c4ca8-cf37-4482-a1be-46d39cb503f9@btinternet.com> <CAHVvXxSKiws7R9v_3z9_8TP-Zsbw9MaXsNKxThLP4odWAcTUCA@mail.gmail.com> Bytes: 8815 On 06/07/2024 12:57, Oscar Benjamin via Python-list wrote: > On Sat, 6 Jul 2024 at 11:55, Rob Cliffe via Python-list > <python-list@python.org> wrote: >> Consider this scenario (which I ran into in real life): >> I want to open a text file and do a lot of processing on the lines >> of that file. >> If the file does not exist I want to take appropriate action, e.g. >> print an error message and abort the program. >> I might write it like this: >> >> try: >> with open(FileName) as f: >> for ln in f: >> print("I do a lot of processing here") >> # Many lines of code here ..... >> except FileNotFoundError: >> print(f"File {FileName} not found") >> sys.exit() >> >> but this violates the principle that a "try" suite should be kept small, >> so that only targeted exceptions are trapped, >> not to mention that having "try" and "except" far apart decreases >> readability. > This is catching a targeted exception (FileNotFoundError) so I think > it is fine. If the intention is just to call sys.exit() on error then > I wouldn't worry too much about having too much code in the try. Just > make sure that you do this in any other place where you open a file as > well. > > One possible improvement is that you could catch the exception and use > its filename attribute: > > except FileNotFoundError as e > print(f"File {e.filename} not found") > > That way if you did catch the wrong FileNotFoundError then at least > you print the correct filename. Good point, Oscar - thank you. (Even if you did omit the colon on the "except" line🙂. I've often thought we should have "Python without colons" as this is a mistake I frequently make.) > > Alternatively: > > except FileNotFoundError as e > if e.filename != FileName: > raise # re-raise if not the intended exception > print(f"File {e.filename} not found") Indeed, that covers all basis. > For readability I would just move the many lines of code into a > separate function. That may not always be convenient (e.g. if the many-lines-of-code needs to access a lot of local variables) but fair enough. Thanks for your answer. Rob Cliffe > > The reason to avoid having too much code in the try mainly applies to > situations where you are going to do something other than call > sys.exit() and the exception is overly generic like ValueError or > TypeError. If the exception can easily be raised by a bug or something > other than the intended cause then it is bad to catch exceptions > around a larger block of code. > > If it is expected that the caller of a function might have good reason > to catch the exception and handle it somehow then it is better to make > a dedicated exception class and raise that instead. When there is only > one place in the code that raises a particular exception type and only > one place that catches it then it is usually going to be clear that > you are catching the expected exception. > > -- > Oscar