Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Discussion options

One more OT comment inspired by #484, as it would have been nice to have in that case:

@erlend-aasland Do you know of any plans to support something like this in Python?

with contextlib.skip(ValueError, KeyError):
    obj.foo = config.get(...)
    obj.bar = config.get(...)
    obj.baz = config.get(...)

The intention being that an exception of the listed types would abort the current statement, but not exit the whole block. Instead, continue with the next line after the one where the exception was raised.

A workaround that comes to mind:

for a, o in option_attributes.items():
    with contextlib.suppress(ValueError, KeyError):
        value = config.get(..., o, ...)
        setattr(obj, a, value)
You must be logged in to vote

Replies: 1 comment · 2 replies

Comment options

Changing the behaviour of __enter__ and __exit__ is not going to happen; it would definitely be a breaking change. Repeatedly using contextlib.suppress seems to be the better solution; no other alternative springs to mind right now.

You must be logged in to vote
2 replies
@erlend-aasland
Comment options

Well, there's contextlib stacks; perhaps those could help here. Disclaimer, I've never explored them nor used them.

https://docs.python.org/3/library/contextlib.html#contextlib.ExitStack

@acolomb
Comment options

acolomb Jul 3, 2024
Maintainer Author

I think it would really need to be a language-level feature, just the syntax for enabling it for a span of code would be borrowed from the context managers. Still think it would be a helpful approach, as in my world at least it is common to have such spans of statements. I don't want to wrap each one individually, but aborting all after one has failed is not the desired behavior. I guess I'll stay stuck with writing wrapper functions for such things, but the setattr() access is definitely uglier than using regular attribute assignment.

The ExitStack stuff looks promising, but not as a readable solution to this problem. Thanks for the pointer though!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.