From 5d759011f278dfddd7cda03e10524ead3c97b706 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Pit-Claudel?= Date: Fri, 27 Aug 2021 03:04:21 -0400 Subject: [PATCH] core: Make gensym more robust by preventing stem collisions --- alectryon/core.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/alectryon/core.py b/alectryon/core.py index 74929b24..c4d1f71f 100755 --- a/alectryon/core.py +++ b/alectryon/core.py @@ -18,7 +18,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from typing import Any, Iterator, List, Tuple, Union, NamedTuple +from typing import Any, Dict, Iterator, List, Tuple, Union, NamedTuple from collections import namedtuple, defaultdict from contextlib import contextmanager @@ -89,9 +89,13 @@ def b16(i): return hex(i)[len("0x"):] class Gensym(): + # Having a global table of counters ensures that creating multiple Gensym + # instances in the same session doesn't cause collisions + GENSYM_COUNTERS: Dict[str, int] = {} + def __init__(self, stem): self.stem = stem - self.counters = defaultdict(lambda: -1) + self.counters = self.GENSYM_COUNTERS.setdefault(stem, defaultdict(lambda: -1)) def __call__(self, prefix): self.counters[prefix] += 1