Skip to content

Instantly share code, notes, and snippets.

Avatar

Nathan Hoad nhoad

View GitHub Profile
View cpycpy.py
import cffi
ffi = cffi.FFI()
ffi.cdef('int PyDict_DelItemString(void *, const char *key);')
lib = ffi.dlopen('libpython3.so')
d = {'foo': 'bar'}
print('before', d)
d_p = ffi.cast('void*', id(d))
lib.PyDict_DelItemString(d_p, ffi.new('char[]', b'foo'))
View tracking attribute accesses
from unittest import mock
class AttributeTrackMock(mock.Mock):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.attr_accesses = []
def __getattr__(self, attr):
res = super().__getattr__(attr)
self.attr_accesses.append(res)
@nhoad
nhoad / code.py
Last active Aug 29, 2015
asynchronous object initialisation
View code.py
import asyncio
class AsyncInitMeta(type):
@asyncio.coroutine
def __call__(cls, *args, **kwargs):
self = cls.__new__(cls)
yield from self.__init__(*args, **kwargs)
return self
View jake
#!/usr/bin/env python2
import argparse
import contextlib
import logging
import re
import os
import sys
import types
View output
from overload import overload
@overload
def hello(name: str):
print('Hello, %s!' % name)
@overload
def hello(name: int):
@nhoad
nhoad / gist:8966377
Last active Jun 23, 2020
Async stdio with asyncio
View gist:8966377
import os
import asyncio
import sys
from asyncio.streams import StreamWriter, FlowControlMixin
reader, writer = None, None
@asyncio.coroutine
def stdio(loop=None):
@nhoad
nhoad / gist:6128860
Last active Dec 20, 2015
The horror of collections.OrderedDict
View gist:6128860
>>> f.keys()
[]
>>> f._OrderedDict__root[0][0][0][0][0][0][0][0][0][0]
[[...], [...], None]
>>> f._OrderedDict__root[0][1][0][1][0][1][0][1][0][1][0]
[[...], [...], None]
You can’t perform that action at this time.