changeset 51549:a452807df09b

nocg: make the utility work are both a decorator and context manager In some case, the context manager version will be simpler.
author Pierre-Yves David <pierre-yves.david@octobus.net>
date Tue, 26 Mar 2024 13:28:52 +0000
parents 1b17eeba9deb
children 463e63aa547c
files mercurial/util.py
diffstat 1 files changed, 21 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- a/mercurial/util.py	Tue Mar 26 11:24:20 2024 +0000
+++ b/mercurial/util.py	Tue Mar 26 13:28:52 2024 +0000
@@ -35,6 +35,7 @@
 import warnings
 
 from typing import (
+    Any,
     Iterable,
     Iterator,
     List,
@@ -1812,7 +1813,7 @@
     return False
 
 
-def nogc(func):
+def nogc(func=None) -> Any:
     """disable garbage collector
 
     Python's garbage collector triggers a GC each time a certain number of
@@ -1825,15 +1826,27 @@
     This garbage collector issue have been fixed in 2.7. But it still affect
     CPython's performance.
     """
-
+    if func is None:
+        return _nogc_context()
+    else:
+        return _nogc_decorator(func)
+
+
+@contextlib.contextmanager
+def _nogc_context():
+    gcenabled = gc.isenabled()
+    gc.disable()
+    try:
+        yield
+    finally:
+        if gcenabled:
+            gc.enable()
+
+
+def _nogc_decorator(func):
     def wrapper(*args, **kwargs):
-        gcenabled = gc.isenabled()
-        gc.disable()
-        try:
+        with _nogc_context():
             return func(*args, **kwargs)
-        finally:
-            if gcenabled:
-                gc.enable()
 
     return wrapper