Skip to content

Instantly share code, notes, and snippets.

@L3viathan
Created August 18, 2023 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save L3viathan/5eb02a16159d35f3cee509022751cb46 to your computer and use it in GitHub Desktop.
Save L3viathan/5eb02a16159d35f3cee509022751cb46 to your computer and use it in GitHub Desktop.
Allow annotated variables as lasting only for a bit
import sys
import threading
from time import sleep
from typing import Annotated, get_origin, get_args
from collections import namedtuple
timeout = namedtuple("timeout", "s")
def deleter(seconds, name, scope):
sleep(seconds)
exec(f"del {name}", scope.f_globals, scope.f_locals)
class A:
def __init__(self):
self.d = {}
def __setitem__(self, name, val):
origin = get_origin(val)
if origin is Annotated:
*_, deadline = get_args(val)
if isinstance(deadline, timeout):
frame = sys._getframe(1)
threading.Thread(
target=deleter,
args=(deadline.s, name, frame)
).start()
self.d[name] = val
def __getitem__(self, item):
return self.d[item]
__annotations__ = A()
# Usage:
x: Annotated[int, timeout(1)] = 23
print(x)
sleep(2)
print(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment