Thanks! And yes, please go ahead and open a PR for that branch.
Yes, a new thread for that would be good, as we need to decide between the different options for implementing the aliasing.
One of the hidden secrets of the contextlib module is that a protocol along these lines kind of exists in order to make contextmanager
CMs usable as function decorators: function decorated with a context manager can only be invoked once · Issue #55856 · python/cpython · GitHub
The implicit CM refresh happens when called rather than through __aenter__
, though.
Trying to generalise the way the chdir CM works to arbitrary CMs would likely be feasible, but I don’t think the problem comes up often enough to be worth worrying about since:
- natively implemented CMs will always be faster than generator based ones, since they don’t have to spend time building and invoking the generator (Edit: for simple cases. For sufficiently complex state, getting to use optimised local variables instead of instance variables as storage can make the trade-offs more complicated. That performance balance is more likely to tip for iterators than it is for CMs, though)
- once you have switched to writing a native CM, pushing/popping values in a list is just as simple to implement as setting/clearing an instance attribute
- there are some CMs where trying to make them reentrant (or even reusable) is a genuinely incoherent request (mostly external resources where once they’re closed they’re released and not accessible anymore), so a general tool that isn’t actually fully general is likely to create more confusion than it resolves