|
7 | 7 | import random |
8 | 8 | import string |
9 | 9 | from typing import Optional, Final, Any, TYPE_CHECKING, Union |
10 | | -from enum import Enum |
| 10 | +from enum import Enum, EnumMeta |
11 | 11 |
|
12 | 12 | if TYPE_CHECKING: |
13 | 13 | from . import sprite, build_defaulting |
@@ -258,7 +258,49 @@ def get_name_nofldr(name: str) -> str: |
258 | 258 | return name[len(fldr) + 2:] |
259 | 259 |
|
260 | 260 | # Parent enum class |
261 | | -class Singleton(Enum): |
| 261 | +class SingletonMeta(EnumMeta): |
262 | 262 |
|
263 | | - def __new__(cls, *args, **kwargs): |
264 | | - return super().__new__(cls, 0) |
| 263 | + def __call__(self, value=0, *args, **kwds): |
| 264 | + if value != 0: |
| 265 | + raise ValueError("Value must be 0.") |
| 266 | + old_bases = self.__bases__ |
| 267 | + self.__bases__ = old_bases + (Enum,) |
| 268 | + result = super().__call__(value, *args, **kwds) |
| 269 | + self.__bases__ = old_bases |
| 270 | + return result |
| 271 | + |
| 272 | + |
| 273 | +if TYPE_CHECKING: |
| 274 | + Singleton = Enum |
| 275 | +else: |
| 276 | + class Singleton(metaclass=SingletonMeta): |
| 277 | + |
| 278 | + def __new__(cls, val=None): |
| 279 | + if cls is Singleton: |
| 280 | + raise TypeError("Singleton cannot be created directly.") |
| 281 | + if hasattr(cls, "INSTANCE"): |
| 282 | + return getattr(cls, "INSTANCE") |
| 283 | + if val == 0: |
| 284 | + return super().__new__(cls) |
| 285 | + raise TypeError("Has no instance.") |
| 286 | + |
| 287 | + def __init__(self, *args, **kwds): |
| 288 | + pass |
| 289 | + |
| 290 | + def __repr__(self): |
| 291 | + return self.__class__.__name__ |
| 292 | + |
| 293 | + def __str__(self): |
| 294 | + return self.__class__.__name__ |
| 295 | + |
| 296 | + def __format__(self, format_spec): |
| 297 | + return str.__format__(str(self), format_spec) |
| 298 | + |
| 299 | + def __hash__(self): |
| 300 | + return hash(self.__class__) |
| 301 | + |
| 302 | + def __reduce_ex__(self, proto): |
| 303 | + return self.__class__, () |
| 304 | + |
| 305 | + def __deepcopy__(self, memo): |
| 306 | + return self |
0 commit comments