|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: LicenseRef-NVIDIA-SOFTWARE-LICENSE |
| 3 | + |
| 4 | + |
| 5 | +# This code was automatically generated across versions from 12.9.1 to 13.1.1. Do not modify it directly. |
| 6 | + |
| 7 | + |
| 8 | +""" |
| 9 | +This is a replacement for the stdlib enum.IntEnum. |
| 10 | +
|
| 11 | +Notably, it has much better import time performance, since it doesn't generate |
| 12 | +and evaluate Python code at startup time. |
| 13 | +
|
| 14 | +It supports the most important subset of the IntEnum API. See `test_enum` in |
| 15 | +`cuda_bindings/tests/test_basics.py` for details. |
| 16 | +""" |
| 17 | + |
| 18 | +from typing import Any, Iterator |
| 19 | + |
| 20 | + |
| 21 | +class FastEnumMetaclass(type): |
| 22 | + def __init__(cls, name, bases, namespace): |
| 23 | + super().__init__(name, bases, namespace) |
| 24 | + |
| 25 | + cls.__singletons__ = {} |
| 26 | + cls.__members__ = {} |
| 27 | + for name, value in cls.__dict__.items(): |
| 28 | + if name.startswith("__") and name.endswith("__"): |
| 29 | + continue |
| 30 | + |
| 31 | + if isinstance(value, tuple): |
| 32 | + value, doc = value |
| 33 | + elif isinstance(value, int): |
| 34 | + doc = None |
| 35 | + else: |
| 36 | + continue |
| 37 | + |
| 38 | + singleton = int.__new__(cls, value) |
| 39 | + singleton.__doc__ = doc |
| 40 | + singleton._name = name |
| 41 | + cls.__singletons__[value] = singleton |
| 42 | + cls.__members__[name] = singleton |
| 43 | + |
| 44 | + for name, member in cls.__members__.items(): |
| 45 | + setattr(cls, name, member) |
| 46 | + |
| 47 | + def __repr__(cls) -> str: |
| 48 | + return f"<enum '{cls.__name__}'>" |
| 49 | + |
| 50 | + def __len__(cls) -> int: |
| 51 | + return len(cls.__members__) |
| 52 | + |
| 53 | + def __iter__(cls) -> Iterator["FastEnum"]: |
| 54 | + return iter(cls.__members__.values()) |
| 55 | + |
| 56 | + def __contains__(cls, item: Any) -> bool: |
| 57 | + return item in cls.__singletons__ |
| 58 | + |
| 59 | + |
| 60 | +class FastEnum(int, metaclass=FastEnumMetaclass): |
| 61 | + def __new__(cls, value: int) -> "FastEnum": |
| 62 | + singleton: FastEnum = cls.__singletons__.get(value) |
| 63 | + if singleton is None: |
| 64 | + raise ValueError(f"{value} is not a valid {cls.__name__}") |
| 65 | + return singleton |
| 66 | + |
| 67 | + def __repr__(self) -> str: |
| 68 | + return f"<{self.__class__.__name__}.{self._name}: {int(self)}>" |
| 69 | + |
| 70 | + @property |
| 71 | + def name(self) -> str: |
| 72 | + return self._name |
| 73 | + |
| 74 | + @property |
| 75 | + def value(self) -> int: |
| 76 | + return int(self) |
0 commit comments