Skip to content

Instantly share code, notes, and snippets.

View agronholm's full-sized avatar

Alex Grönholm agronholm

  • NextDay Solutions Oy
  • Nurmijärvi, Finland
View GitHub Profile
@agronholm
agronholm / wrapperdemo.py
Created November 10, 2019 13:05
How do I properly wrap a class method?
from functools import wraps
class A:
@classmethod
def method(cls):
print('cls = %s' % cls.__name__)
class B(A):
@agronholm
agronholm / triotest.py
Created September 29, 2019 21:17
Test handling of an exception when the nursery has no active host task
import trio
async def error_after(delay):
await trio.sleep(delay)
raise Exception('foo')
async def somegenerator():
try:
@agronholm
agronholm / importhook.py
Created September 15, 2019 20:11
Typeguard import hook for automatic code instrumentation
import ast
import re
import sys
from importlib.machinery import SourceFileLoader
from importlib.abc import MetaPathFinder
from importlib.util import decode_source, cache_from_source
from typing import Iterable
from unittest.mock import patch
@agronholm
agronholm / pytest_plugin.py
Last active September 30, 2018 21:22
Async pytest plugin
from functools import partial
from inspect import iscoroutinefunction
import pytest
import hyperio
try:
from async_generator import isasyncgenfunction
except ImportError:
@agronholm
agronholm / conftest.py
Created August 9, 2018 19:36
SQLAlchemy asyncio threading fixture
@pytest.fixture(scope='session', autouse=True)
def sqlalchemy_thread_check(connection):
"""Raise an exception is SQL is executed in the event loop thread in the application code."""
def check_thread(*args):
if asyncio._get_running_loop():
frames = [f for f in extract_stack()[:-1] if 'ebserver' in f.filename]
if frames:
raise RuntimeError(f'SQL executed in the event loop thread '
f'(from {frames[-1].filename}:{frames[-1].lineno})')
@agronholm
agronholm / countertest.py
Last active July 30, 2018 18:41
Thread safety test for the += operator
from threading import Thread
counter = 0
threads = []
def increment():
global counter
for _ in range(500000):
counter += 1
@agronholm
agronholm / trio-threadblock.py
Last active June 25, 2018 07:16
Trio version of "async with threadpool():"
import gc
import inspect
import threading
import trio
from trio import run_sync_in_worker_thread
from trio.hazmat import (
spawn_system_task, wait_task_rescheduled, reschedule, current_task, Error, Value, Abort)
@agronholm
agronholm / nursery.py
Last active May 1, 2018 12:07
Asyncio nursery
import inspect
from asyncio import get_event_loop, gather, Task, wait
from concurrent.futures import Executor, ThreadPoolExecutor, ProcessPoolExecutor
from functools import wraps, partial
from typing import Callable, Union, TypeVar, Awaitable, List, Dict
T_Retval = TypeVar('T_Retval')
class MultiError(Exception):
@agronholm
agronholm / callee.py
Created September 27, 2017 21:46
Sample trio WAMP applications
import logging
import trio
from wampproto.impl.client.trio import TrioWAMPClient
def procedure_handler(name):
return 'Hello, {}!'.format(name)
@agronholm
agronholm / setup.cfg
Created September 4, 2017 22:24
wampproto's packaging configuration
[metadata]
name = wampproto
description = WAMP (Web Application Message Protocol) state-machine based protocol implementation
long_description = file: README.rst
author = Alex Grönholm
author_email = [email protected]
url = https://github.com/agronholm/wampproto
license = MIT
license_file = LICENSE
keywords = wamp, websockets