Coverage for src/gitlabracadabra/singleton.py: 86%
10 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-10 17:02 +0100
« prev ^ index » next coverage.py v7.6.12, created at 2025-03-10 17:02 +0100
1#
2# Copyright (C) 2019-2025 Mathieu Parent <math.parent@gmail.com>
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU Lesser General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU Lesser General Public License for more details.
13#
14# You should have received a copy of the GNU Lesser General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
17from __future__ import annotations
19from typing import TYPE_CHECKING
21if TYPE_CHECKING: 21 ↛ 22line 21 didn't jump to line 22 because the condition on line 21 was never true
22 from typing import Any, ClassVar
25class SingletonMeta(type):
26 """MetaClass to implement Singleton pattern.
28 Usage:
29 class Registries(metaclass=SingletonMeta):
30 # ...
31 """
33 _instances: ClassVar[dict[type, object]] = {}
35 def __call__(cls, *args: Any, **kwargs: dict[Any, Any]) -> object:
36 """Get singleton for the calling class.
38 Args:
39 args: Passed to method.
40 kwargs: Passed to method.
42 Returns:
43 The singleton.
44 """
45 if cls not in cls._instances:
46 cls._instances[cls] = super().__call__(*args, **kwargs)
47 return cls._instances[cls]