Return to

Useful Python code

Post useful Python code or links to it.

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.

import antigravity


But on a more serious note list comps are incredibly useful one-liners. I typically find them quite useful for filtering like below:

result = [iter for iter in list if iter {<>=} condition]
1 Like

You know, in Ruby that would be{|e| e matches some condition}

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
    else: # called by a function

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: