Skip to content

Instantly share code, notes, and snippets.

@ZechCodes
Last active September 15, 2023 22:52
Show Gist options
  • Save ZechCodes/5c2bf1ab83c7fa3cd9a34e1fc83d0028 to your computer and use it in GitHub Desktop.
Save ZechCodes/5c2bf1ab83c7fa3cd9a34e1fc83d0028 to your computer and use it in GitHub Desktop.
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