08.04.21 17:59, anthony.flury via Python-ideas пише: > I was wondering whether a worthwhile extension might be to allow the > `with` statement to have an `except` and `else` clauses which would > have the same > semantics as wrapping the `with` block with a try - for example the > above would now look like: > > > with open('config.cfg', 'r') as cfg: > # Process the open file > config = load_config(cfg) > except FileNotFound: > logging.info('Config file not found - using default configuration') > except PermissionError: > logging.warning('Cannot open config .cfg - using default > configuration') > config = default_config() > else: > logging.info('Using config from config.cfg')
A year or two ago I proposed the same syntax with different semantic: to catch only exceptions in the context manager, not in the with block. Exceptions in the with block you can catch by adding try/except around the with block, exceptions in the with block and the context manager you can catch by adding try/except around the with statement, but there is no currently way to catch only exceptions in the context manager. It is quite a common problem, I encounter it several times per year since then. I still have a hope to add this feature, and it will conflict with your idea. _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/OMAEC4EPAWBXBIHHLY75M6GTN6OL4MP4/ Code of Conduct: http://python.org/psf/codeofconduct/