Skip to content

Instantly share code, notes, and snippets.

@jsbueno
jsbueno / example decorator above being used interactivelly
Last active Feb 11, 2020
A decorator to be applied on other decorators that make then automatically work for both sync and async functions (coroutine functions)
View example decorator above being used interactivelly
In [97]: @log_run
...: def ble(x):
...: time.sleep(0.5)
...: print(x)
...:
...:
In [98]: @log_run
...: async def bli(x):
...: await asyncio.sleep(1)
@jsbueno
jsbueno / create_file_with_filter.py
Created Dec 20, 2019
Gist to enable filtering out file-name-patterns when creating an Archive (zipfile, tarball) with Python code
View create_file_with_filter.py
# WARNING: this implementation depends on the internal implementation of shutil.makefile as it is up to Python 3.8.0
# it might change without notice to use pathlib internally, and this will break
import shutil
import re
from unittest.mock import patch
def create_archive_with_filter(*args, filter_out_pattern="", **kwargs):
@jsbueno
jsbueno / slide_tail_rec.py
Created Oct 28, 2019
Slides using jsbueno/terminedia for quickly explaining the concept of tail recursion optimizations. Used to illustrate a lightning talk on a proof of concept decorator for usng async tasks to have tail-recursion optimization: https://gist.github.com/jsbueno/7644e94bbaa4fbaa8b5e8f4d2bd71425
View slide_tail_rec.py
import time
import terminedia as TM
from terminedia import V2, Color, pause, shape
SIZE = 170, 50
def hto8(pos):
return (V2(pos) * 0.0625).as_int
@jsbueno
jsbueno / asynctailcall.py
Created Oct 22, 2019
Proof of concept for Python Tail Call Optmization using asyncio
View asynctailcall.py
import asyncio, types, inspect, sys
max_stack = 0
def stack_depth():
count = 0
f = sys._getframe()
while f.f_back:
count += 1
f = f.f_back
@jsbueno
jsbueno / gist:5f5d200fd77dd1233c3063ad6ecb2eee
Created Aug 9, 2019
Python JSON Encoder able to encode arbitrary precision decimals as numbers
View gist:5f5d200fd77dd1233c3063ad6ecb2eee
import json, re, uuid
class JsonDecimalAwareEncoder(json.JSONEncoder):
def __init__(self, *args, **kw):
self.original_numbers = {}
super().__init__(*args, **kw)
def default(self, obj):
if isinstance(obj, decimal.Decimal):
key = uuid.uuid4()
@jsbueno
jsbueno / itercontext.py
Last active Jul 12, 2019
Python recipe to enter an arbitrary number of contexts at once
View itercontext.py
from contextlib import contextmanager
import sys
@contextmanager
def itercontext(*args):
contexts = [context.__enter__() for context in args]
try:
yield contexts
View iterate_non_blocking.py
"""
Implements a for loop iterator wrapper to be used
in sync-loops inside async functions, so that control
can be yielded to the asyncio-loop after a certain
timeout or at each N iterations.
The original "in line" implementation, idea and needed were presented by
Nikita Melentev at the e-mail to Python-ideas list
stored at:
@jsbueno
jsbueno / awaitable_class.py
Created Jun 13, 2019
Snippet with metaclass enabling a class to have an async __init__ method in Python.
View awaitable_class.py
import inspect
from functools import wraps
def async_init_wrapper(func):
def wrapper_stage1(instance):
async def wrapper_stage2(*args, **kw):
value = await func(instance, *args, **kw)
if value is not None:
raise TypeError("__async_init__() should return None")
return instance
@jsbueno
jsbueno / plot_example.py
Created May 16, 2019
Example of raw plotting 2d funciton with pygame
View plot_example.py
import pygame
larg, alt = 800, 600
intervalo = -10, 10
fator_y = 1.0
tela = pygame.display.set_mode((larg, alt))
f_x= lambda x:3 * x ** 2 + 2 * x + 4
@jsbueno
jsbueno / Usage example
Created May 16, 2019
matplotlib - plot programatic function without explictly generating all Y points into a ndarray
View Usage example
import numpy as np
from matplotlib import pyplot as plt
import math
# This simple example still requires X points in an ndarray, old-style:
x = np.arange(0, 10, .1)
# but for y data, we can use the class in the snippet above:
# replace math.sin for any function you want.
# Not that a scalar function is used, not one that operates on ndarrays (so, not np.sin)