[Python-ideas] Generalized version of contextlib.close

Giampaolo Rodola' g.rodola at gmail.com
Sun Apr 1 16:57:56 EDT 2018


On Mon, Mar 26, 2018 at 10:35 AM, Roberto Martínez <
robertomartinezp at 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 at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
>
+1

-- 
Giampaolo - http://grodola.blogspot.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180401/175f91a6/attachment.html>


More information about the Python-ideas mailing list