Skip to content

Instantly share code, notes, and snippets.

View ambv's full-sized avatar
🐍
CPython Dev in Residence

Łukasz Langa ambv

🐍
CPython Dev in Residence
View GitHub Profile
@ambv
ambv / ensure_dead_with_parent.py
Last active March 10, 2017 01:02
Defensive programming for unhandled errors. Add this to preexec_fn= in your subprocess calls.
import ctypes
import sys
import signal
def ensure_dead_with_parent():
"""A last resort measure to make sure this process dies with its parent.
Defensive programming for unhandled errors.
"""
if not sys.platform.startswith('linux'):
return # not supported on OS X, Windows, etc. Use process groups.
@ambv
ambv / clog_the_event_loop.py
Created June 2, 2016 19:43
In which rogue call_soons starve cooperating callbacks.
import asyncio
import time
loop = asyncio.get_event_loop()
async def go(sleep):
await asyncio.sleep(sleep)
print('I slept', sleep, 'seconds')
def clog(sleep):
@ambv
ambv / per_instance_memoization.py
Last active May 26, 2016 08:22
Per-instance memoization in Python. The per-instance lazy binder is thread-safe.
from functools import lru_cache
import threading
import time
def per_instance(factory, *factory_args, **factory_kwargs):
"""Applies the given decorator on a per-instance basis."""
def lazy_binder(method):
"""Replaces the method just in time when it is first invoked."""
@ambv
ambv / post_iteration_deletion.py
Created May 21, 2016 23:52
Requires Python 3.3+
from contextlib import ExitStack
d = {index: str(index) for index in range(100)}
with ExitStack() as stack:
for key in d:
if key % 13 == 0:
stack.callback(d.pop, key)
print(d)
def func():
try:
raise ValueError('ve')
except Exception as e:
handle_exception(e)
def handle_exception(e):
if 'some terrible thing' in e.args[0]:
raise
@ambv
ambv / exceptions.py
Created March 14, 2016 04:11
Behavior of exception name binding in Python
from __future__ import print_function
import sys
def example1():
try:
pass # nothing is raised
except Exception as e1:
pass
#!/usr/bin/env python3
"""Repacks entries in a ZIP file so that they become correctly zipimportable \
in Python 3.5. See https://bugs.python.org/issue25710 for details.
"""
import argparse
from pathlib import Path
import importlib._bootstrap_external
import sys

Keybase proof

I hereby claim:

  • I am ambv on github.
  • I am ambv (https://keybase.io/ambv) on keybase.
  • I have a public key whose fingerprint is E3FF 2839 C048 B25C 084D EBE9 B269 95E3 1025 0568

To claim this, I am signing this object:

@ambv
ambv / gist:ff0c793c050bbd701c7b
Created June 15, 2014 02:13
Steps to reproduce the Unicode bug
$ pip install testunicodepackagedependant
Downloading/unpacking testunicodepackagedependant
Downloading testunicodepackagedependant-1.0.tar.gz
Storing download in cache at /Users/ambv/.pip/cache/https%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2Ft%2Ftestunicodepackagedependant%2Ftestunicodepackagedependant-1.0.tar.gz
Running setup.py (path:/private/tmp/testestest/build/testunicodepackagedependant/setup.py) egg_info for package testunicodepackagedependant
Downloading/unpacking testunicodepackage==1.0 (from testunicodepackagedependant)
Downloading testunicodepackage-1.0.tar.gz
Cleaning up...
Exception:
@ambv
ambv / state.py
Last active February 28, 2016 00:05
Stateful methods with PEP 443 single-dispatch generic functions.
from decimal import Decimal
from functools import singledispatch
#
# @singledispatch has to be moved inside __init__ to
# make registration work per instance.
#
class State:
def __init__(self):