Skip to content

gh-144386: Update equivalent code for "with", "async with" and "async for"#144472

Open
serhiy-storchaka wants to merge 1 commit intopython:mainfrom
serhiy-storchaka:docs-special-methods-lookup
Open

gh-144386: Update equivalent code for "with", "async with" and "async for"#144472
serhiy-storchaka wants to merge 1 commit intopython:mainfrom
serhiy-storchaka:docs-special-methods-lookup

Conversation

@serhiy-storchaka
Copy link
Member

@serhiy-storchaka serhiy-storchaka commented Feb 4, 2026

They use special method lookup for special methods.


📚 Documentation preview 📚: https://cpython-previews--144472.org.readthedocs.build/

…"async for"

They use special method lookup for special methods.
@tanloong
Copy link
Contributor

tanloong commented Feb 5, 2026

I happened to notice that there might be a small point to adjust. The updated equivalent code manager.__enter__ could look up __enter__ in the instance attributes, but the with-statement does not.

import sys
class CM:
    def __init__(self):
        def __enter__():
            pass
        def __exit__(*exc_details):
            pass
        self.__enter__ = __enter__
        self.__exit__ = __exit__


# Not works: TypeError: 'CM' object does not support the context manager protocol (missed __exit__ method)
with CM():
    pass

# Works
manager = CM()
enter = manager.__enter__
exit_ = manager.__exit__
value = enter()
hit_except = False
try:
    TARGET = value
except:
    hit_except = True
    if not exit(*sys.exc_info()):
        raise
finally:
    if not hit_except:
        exit_(None, None, None)

@serhiy-storchaka
Copy link
Member Author

Yes, this is what the added note for.

@tanloong
Copy link
Contributor

tanloong commented Feb 5, 2026

Oops, I missed that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting core review docs Documentation in the Doc dir needs backport to 3.13 bugs and security fixes needs backport to 3.14 bugs and security fixes skip news

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

2 participants