I started a utils repo, mainly just to remind myself how to do things, and for the ability to copy/paste when I start a new project; however, I also have it for storing awesome one-liners I read and know I’ll forget.
That’s pretty nifty. Sadly Ruby is one of those languages that’s on my not so short “I should learn this language” list that I never seem to have time to get around to.
Here’s a new one, pulled from a video by david beazely:
from sys import _getframe
import asyncio
def from_coroutine():
return _getframe(2).f_code.co_flags & 0x380
def is_async(x):
"""Determine whether this function was invoked by a coroutine"""
if from_coroutine(): # called by a coroutine
foo(x)
else: # called by a function
bar(x)
This is an interesting one that returns different values depending on whether it was called by an async coroutine or a regular function, allowing you to create functions with a single, less confusing entry point, i.e., not having foo_sync() and foo_async() all over the place.
Timestamped, if you want to hear him explain it better: