# HG changeset patch # User Pierre-Yves David # Date 2024-03-26 13:28:52 # Node ID a452807df09b5b07e0c5830ee1b9271f4f1df81e # Parent 1b17eeba9deb66026b5d740904cefb847f0b2872 nocg: make the utility work are both a decorator and context manager In some case, the context manager version will be simpler. diff --git a/mercurial/util.py b/mercurial/util.py --- a/mercurial/util.py +++ b/mercurial/util.py @@ -35,6 +35,7 @@ import traceback import warnings from typing import ( + Any, Iterable, Iterator, List, @@ -1812,7 +1813,7 @@ def never(fn): 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 @@ def nogc(func): 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