From patchwork Thu Jan 14 22:17:48 2016 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: [1,of,2] extensions: add get contextmanager to avoid common pattern From: Laurent Charignon X-Patchwork-Id: 12776 Message-Id: To: Date: Thu, 14 Jan 2016 14:17:48 -0800 # HG changeset patch # User Laurent Charignon # Date 1452809804 28800 # Thu Jan 14 14:16:44 2016 -0800 # Node ID c1ba4521aea0906874fe7de5bee156d5070c0e56 # Parent e6e34c4e391668c5d8af8f98c004a27c77b1e2fa extensions: add get contextmanager to avoid common pattern Before this patch, people were sometimes using the following pattern: try: m = extensions.find(name) ... except KeyError: pass This patch simplifies the pattern with context managers as follow: with extensions.get(name) as m: ... diff --git a/mercurial/extensions.py b/mercurial/extensions.py --- a/mercurial/extensions.py +++ b/mercurial/extensions.py @@ -7,6 +7,7 @@ from __future__ import absolute_import +from contextlib import contextmanager import imp import os @@ -41,6 +42,13 @@ def extensions(ui=None): if module and enabled(name): yield name, module +@contextmanager +def get(name): + try: + yield find(name) + except KeyError: + pass + def find(name): '''return module with given extension name''' mod = None