Fix @noreentry breaking contextlib ExitStack support for decorated context managers — Closes #306#307
Merged
conradbzura merged 2 commits intoJul 13, 2026
Conversation
Pushing a guarded context manager onto an ExitStack or AsyncExitStack raised TypeError, the error the decorator emits for bare functions. contextlib looks special methods up on the type and calls them unbound, so type(cm).__enter__(cm) reaches the descriptor itself rather than a bound wrapper, and __call__ rejected it. WorkerPool was affected: a pool could not be composed onto a stack alongside other resources. Record the owning class via __set_name__ and treat an owned descriptor invoked with an instance of its owner as the bound call it actually is, delegating through __get__ so the guard, the coroutine-ness, and the wrapper cache all still apply. Class-level access keeps returning the descriptor, so introspection is unchanged, and a bare function still has no owner and is still rejected. Teardown works the same way: contextlib registers exit as a method of the type, so a guarded __exit__ receives its exception triple through the same path.
Pin the reported failure at both the utility and the WorkerPool level: a guarded manager enters through ExitStack and AsyncExitStack, and the guard still rejects a second entry there. Guard the argument-forwarding half of the contract, which nothing exercised. contextlib registers teardown as a method of the type, so a guarded exit is routed through the descriptor with its exception triple as trailing arguments; every prior test entered with no arguments at all, so an implementation that dropped them silently passed. Cover the exception details reaching a guarded exit through both stacks, and argument forwarding on a direct unbound call. Pin the guard as shared across the bound and unbound call forms, by example and by a property over arbitrary interleavings of the two, so the widened dispatch cannot become a way around single-use semantics. Cover a subclass entering through a stack, since dispatch admits any instance of the owning class rather than only exact instances, and the plain statement form, which had no coverage of its own. Rename the bare-function test to say what it asserts: it calls an owned descriptor with no instance, which is a distinct rejection branch from a genuinely unowned function. Drop the unbound-access test, whose only assertion could not fail.
13c191c to
63ad271
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
contextlibenters a context manager by looking the special method up on the type and calling it unbound (cls = type(cm); _enter = cls.__enter__; result = _enter(cm)). For a@noreentry-decorated__enter__that class access returns the descriptor itself, socontextlibcalled it directly and landed in__call__— whose only job was to reject bare functions. Any guarded context manager therefore blew up withTypeError: @noreentry only decorates methods, not bare functionsthe moment it was pushed onto a stack.WorkerPoolis affected onreleasetoday: a pool cannot be composed onto anAsyncExitStackalongside other resources.Record the owning class with
__set_name__and teach__call__to recognise the unbound-call form — an owned descriptor invoked with an instance of its owner is the bound call it actually is — delegating through__get__so the guard, the coroutine-ness, and the per-instance wrapper cache all still apply.__get__is deliberately left alone: class-level access keeps returning the descriptor, soasyncio.iscoroutinefunction,__name__, and the existing zero-argumentTypeErrorall behave exactly as before. A bare function never gets an owner, so it is still rejected.The alternative — having
__get__(None, ...)return an unbound wrapper — was prototyped and rejected: it silently breaksiscoroutinefunctionon the class attribute (the wrapper is a sync function returning a coroutine) and changes the bare-function error message. Discriminating in__call__preserves all ten pre-existing tests unchanged.Closes #306
Proposed changes
Record the owning class
Add
__set_name__, which Python calls when the descriptor is bound into a class body. A bare module-level function never triggers it, so_ownerstaysNone— and that absence is precisely what distinguishes a genuine bare-function invocation fromcontextlib's unbound call.Recognise the unbound-call form in
__call____call__now delegates when the descriptor is owned and its first argument is an instance of that owner, forwarding the remaining arguments; otherwise it raisesTypeErroras before. Delegation routes through__get__, reusing the existing per-instance wrapper rather than re-implementing the guard, so bound and unbound calls share one guard and one piece of state.isinstance(nottype(...) is) is used deliberately:contextliblooks the method up ontype(cm), which may be a subclass of the class the method was defined on.This also fixes teardown, which the issue did not mention:
contextlibregisters exit asMethodType(cls.__exit__, cm), so a guarded__exit__is routed through the same path and receives its exception triple as trailing arguments.Correct the decorator's parameter documentation
:param fn:advertised "the bound instance or class method to decorate", but@classmethodcomposed with@noreentryraisesTypeErrorin both stacking orders and always has. Narrow the claim to what the decorator actually accepts.Test cases
TestNoReentry__enter__is guardedExitStackTestNoReentryRuntimeErrorTestNoReentry__aenter__is guardedAsyncExitStackTestNoReentryRuntimeErrorTestNoReentry__enter__and__exit__are both guardedExitStackbody__exit__receives the exception details and the exception propagatesTestNoReentry__aenter__and__aexit__are both guardedAsyncExitStackbody__aexit__receives the exception details and the exception propagatesTestNoReentrywithstatementExitStackRuntimeErrorTestNoReentryRuntimeErrorTestNoReentry__enter__is guarded on the baseExitStackTestNoReentrywithstatementTestNoReentryasync withstatementTestNoReentryTestNoReentry@noreentry-decorated module-level function owned by no classTypeErrorTestNoReentryTypeErrorTestNoReentryTypeErrorTestWorkerPoolWorkerPool, whose__aenter__is guardedAsyncExitStackand the stack unwindsTwo pre-existing tests are also reworked:
test_noreentry_bare_function_raises_erroris renamed to say what it actually asserts (it calls an owned descriptor with no arguments — a distinct rejection branch from a genuinely unowned function, which case 13 now covers), andtest_noreentry_unbound_access_returns_descriptoris dropped, its only assertion beingassert unbound is not None, which cannot fail.Mutation-checked: cases 5, 6, and 12 fail if
__call__stops forwarding trailing arguments, and case 9 fails ifisinstanceis weakened totype(...) is. Before these were added, both mutations passed the entire 146-test suite.