Skip to content

Instantly share code, notes, and snippets.

@autf
autf / Makefile
Last active March 21, 2023 05:30
An offical example of embedding Python in C + an unofficial Makefile
run: pt
./pt
pt: printime.c
cc `python3-config --cflags` -o $@ $^ `python3-config --ldflags --embed`
clear:
rm -f pt
find -name '*.rs' -exec bash -c \
'wc -c $0; base64 -w0 < $0 | wc -c; ruby -r uri -e "p URI.encode_www_form_component(STDIN.read).size" < $0; echo' {} \;
import timeit
import random
import array
setups = """xs = array('i', [0]) * n #array
xs = [0] * n #list
"""
# xs = [None] * n #list
# ^^^^ make no difference in timing
from timeit import Timer
cases = list(ln.split('#') for ln in
"""array('i', [0]) * n #arr * n
array('i', [0]*n) #arr(lst*n)
array('i', range(n)) #arr(range)
array('i', (0 for _ in range(n))) #arr(0 for range)
""".splitlines())
for i in range(8):
import sys
from operator import gt, ge
cmp = ge
def search(a, x):
print('search:', x)
i, j = 0, len(a)
while i < j:
h = (i+j) // 2
import sys, itertools
for _, it in itertools.groupby(sorted(sys.stdlib_module_names), lambda s: s[0]):
for x in sorted(it): print(x)
print()
import dis, json, sys, inspect, base64
bs = b'this is bytes'
plex = 1+2j
def code2dict(co):
d = {}
for k, v in inspect.getmembers(co):
# isbuildtin(x) -> Is x a built-in FUNCTION or METHOD?
if k.startswith('co_') and not inspect.isbuiltin(v):
import dis
import rich # not in std
class Foo:
@staticmethod
def bar(co):
rich.inspect(co)
for c in co.co_consts:
if hasattr(c, 'co_code'):
Foo.bar(c)
class T:
...
def _m(my): print('m', my)
T.m = _m
@classmethod
def _cm(cls): print('cm', cls)
T.cm = _cm
## ...OR
@autf
autf / class_as_decorator.py
Created February 14, 2022 07:14
__new__ quacks like __call__
class trace:
lv = 0
# https://docs.python.org/3/reference/datamodel.html#object.__new__
def __new__(cls, fn):
def wrapper(x):
indent = 4 * cls.lv * ' '
cls.lv += 1
print(indent + f'f({x})')
res = fn(x)