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/>.

16

17 from __future__ import annotations

18

19 from typing import TYPE_CHECKING

20

21 if TYPE_CHECKING: 21 ↛ 22 line 21 didn't jump to line 22 because the condition on line 21 was never true

22 from typing import Any, ClassVar

23

24

25 class SingletonMeta(type):

26 """MetaClass to implement Singleton pattern.

27

28 Usage:

29 class Registries(metaclass=SingletonMeta):

30 # ...

31 """

32

33 _instances: ClassVar[dict[type, object]] = {}

34

35 def __call__(cls, *args: Any, **kwargs: dict[Any, Any]) -> object:

36 """Get singleton for the calling class.

37

38 Args:

39 args: Passed to method.

40 kwargs: Passed to method.

41

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]