Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #196246 > unrolled thread

Suggested python feature: allowing except in context maneger

Started byYair Eshel <guruyaya@gmail.com>
First post2024-06-13 13:01 +0300
Last post2024-06-13 13:01 +0300
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Suggested python feature: allowing except in context maneger Yair Eshel <guruyaya@gmail.com> - 2024-06-13 13:01 +0300

#196246 — Suggested python feature: allowing except in context maneger

FromYair Eshel <guruyaya@gmail.com>
Date2024-06-13 13:01 +0300
SubjectSuggested python feature: allowing except in context maneger
Message-ID<mailman.130.1718284531.2909.python-list@python.org>
Hello. I read this is a good place to give some suggestions for features in
python. If not, please let me know.

This is an example of a code I normally use in my everyday work:
import logging
try:
  with open('sample_data/READM.md') as f:
    print (len(f.read()))
except FileNotFoundError:
  logging.error("File not found")


As you can see I have 2 levels of indentation, which can add some pain to
the work with the context manager. This code without context manager, can
be replaced by this code:

import logging
try:
  f = open('sample_data/READM.md') as f:
  print (len(f.read()))
except FileNotFoundError:
  logging.error("File not found")
finally:
  f.close()

And while this offers less indentations, it skips the usage of the very
handy context manager.

I would like to suggest an alternative syntax, that will, in a sense, apply
the best of both worlds:

import logging
with open('sample_data/README.md') as f:
  print (len(f.read()))
except FileNotFoundError:
  logging.error("File not")

As "with" applies the behavior of the "try / finally" it feels like a
natural part of this syntax. This could provide a cleaner code.
If this idea is accepted, there are several things that need to be
discussed, like what to do with "else" or "finally" statement following a
context manager. I'm not sure about the proper way to handle this.

With hopes for an even more readable future
Yair
-- 
בברכה,
יאיר אשל כהנסקי
מתכנת וטכנאי מילים
https://www.inspect-element.net/YouAreHere/#/start

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web