Last active
September 15, 2023 22:52
-
-
Save ZechCodes/5c2bf1ab83c7fa3cd9a34e1fc83d0028 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Type, TypeVar | |
class Sentinel: | |
def __new__(cls): | |
instance = super().__new__(cls) | |
cls.__new__ = lambda _: instance | |
return instance | |
S = TypeVar("S", bound=Sentinel) | |
def create_sentinel(name: str) -> tuple[Type[S], S]: | |
sentinel_type = type(name, (Sentinel,), {}) | |
return sentinel_type, sentinel_type() | |
DemoSentinel, demo_sentinel = create_sentinel("DemoSentinel") | |
def example(value: int | DemoSentinel = demo_sentinel): | |
if value is demo_sentinel: | |
print("Sentinel set") | |
else: | |
print("Value", value) | |
example(10) | |
example(DemoSentinel()) | |
example() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment