Skip to content

Instantly share code, notes, and snippets.

@decorator-factory
Created February 22, 2022 18:35
Show Gist options
  • Save decorator-factory/c0840d7c663f017d49a4ceda0419d52c to your computer and use it in GitHub Desktop.
Save decorator-factory/c0840d7c663f017d49a4ceda0419d52c to your computer and use it in GitHub Desktop.
Cursed Python - inspired by `jtolio/gls`
import inspect
from collections.abc import Iterator
from asyncio import run, sleep, create_task
from types import FrameType
from typing import Optional
async def _setup_(f):
return await f
async def _0_(f):
return await f
async def _1_(f):
return await f
def frames(base: Optional[FrameType]) -> Iterator[FrameType]:
while base is not None:
yield base
base = base.f_back
def get_id() -> int:
total = 0
for frame in frames(inspect.currentframe()):
name = frame.f_code.co_name
if name == "_setup_":
return total
elif name == "_0_":
total = total * 2
elif name == "_1_":
total = total * 2 + 1
return None
async def func3(x):
print("sleeping...", x)
await sleep(0.5)
print("done", x)
print("id of", x, get_id())
async def func2(x):
return await func3(x)
async def func1(x):
return await func2(x)
async def main():
task1 = create_task(
_setup_(_0_(_1_(_0_(_0_(_1_(
func1("foo")
))))))
)
task2 = create_task(
_setup_(_1_(_0_(_0_(_0_(_1_(_1_(
func1("bar")
)))))))
)
await task1
await task2
run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment