Source code for jgdv.structs.metalord.singleton

 1#!/usr/bin/env python3
 2"""
 3
 4
 5"""
 6# Imports:
 7from __future__ import annotations
 8
 9# ##-- stdlib imports
10import datetime
11import enum
12import functools as ftz
13import itertools as itz
14import logging as logmod
15import pathlib as pl
16import re
17import time
18import types
19import collections
20import contextlib
21import hashlib
22from copy import deepcopy
23from uuid import UUID, uuid1
24from weakref import ref
25import atexit # for @atexit.register
26import faulthandler
27# ##-- end stdlib imports
28
29from .core import MetalordCore
30# ##-- types
31# isort: off
32import abc
33import collections.abc
34from typing import TYPE_CHECKING, cast, assert_type, assert_never
35from typing import Generic, NewType
36# Protocols:
37from typing import Protocol, runtime_checkable
38# Typing Decorators:
39from typing import no_type_check, final, override, overload
40
41if TYPE_CHECKING:
42    from jgdv import Maybe
43    from typing import Final
44    from typing import ClassVar, Any, LiteralString
45    from typing import Never, Self, Literal
46    from typing import TypeGuard
47    from collections.abc import Iterable, Iterator, Callable, Generator
48    from collections.abc import Sequence, Mapping, MutableMapping, Hashable
49
50##--|
51
52# isort: on
53# ##-- end types
54
55##-- logging
56logging = logmod.getLogger(__name__)
57##-- end logging
58
59# Vars:
60
61# Body:
62
[docs] 63class MLSingleton(MetalordCore): 64 """ 65 Metaclass for enforcing singletons 66 67 with force_new=True, dont reuse the singleton 68 """ 69 def __call__(cls, *args:Any, **kwargs:Any): 70 match kwargs.pop("force_new", False): 71 case True: 72 obj = object.__new__(cls) 73 obj.__init__(*args, **kwargs) 74 return obj 75 case _ if not hasattr(cls, "__inst"): 76 logging.debug("Creating Singleton %s", cls.__name__) 77 obj = object.__new__(cls) 78 obj.__init__(**kwargs) 79 setattr(cls, "__inst", obj) 80 81 return getattr(cls, "__inst")