Generalized version of contextlib.close
Hi, sometimes I need to use contextlib.close but over methods with a different name, for example stop(), halt(), etc. For those cases I have to write my own contextlib.close specialized version with a hard-coded method name. I think adding a "method" argument to contextlib.close can be very useful: @contextmanager def closing(thing, method="close"): try: yield thing finally: getattr(thing, method)() Or maybe something even more generic: @contextmanager def calling(fn, *args, **kwargs): try: yield finally: fn(*args, **kwargs) Best regards, Roberto
On 03/26/2018 10:35 AM, Roberto Martínez wrote:
Hi,
sometimes I need to use contextlib.close but over methods with a different name, for example stop(), halt(), etc. For those cases I have to write my own contextlib.close specialized version with a hard-coded method name.
I think adding a "method" argument to contextlib.close can be very useful:
@contextmanager def closing(thing, method="close"): try: yield thing finally: getattr(thing, method)()
+1
On Mon, Mar 26, 2018 at 10:35 AM, Roberto Martínez < robertomartinezp@gmail.com> wrote:
Hi,
sometimes I need to use contextlib.close but over methods with a different name, for example stop(), halt(), etc. For those cases I have to write my own contextlib.close specialized version with a hard-coded method name.
I think adding a "method" argument to contextlib.close can be very useful:
@contextmanager def closing(thing, method="close"): try: yield thing finally: getattr(thing, method)()
Or maybe something even more generic:
@contextmanager def calling(fn, *args, **kwargs): try: yield finally: fn(*args, **kwargs)
Best regards, Roberto
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
+1 -- Giampaolo - http://grodola.blogspot.com
On 26 March 2018 at 18:35, Roberto Martínez
@contextmanager def calling(fn, *args, **kwargs): try: yield finally: fn(*args, **kwargs)
I'd be more amenable to a proposal along these lines (rather than adding a parameter to closing), as it more closely resembles the way that contextlib.ExitStack.callback already works: with contextlib.ExitStack() as stack: stack.callback(fn, *args, **kwds) ... In cases where you just want to call a single operation and don't need the extra complexity and overhead of the dynamic stack, then it would be nice to be able to instead write: with contextlib.callback(fn, *args, **kwds): ... Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia
participants (4)
-
francismb
-
Giampaolo Rodola'
-
Nick Coghlan
-
Roberto Martínez