Skip to content

Instantly share code, notes, and snippets.

@jsbueno
jsbueno / deltafloat.py
Created January 9, 2015 12:06
DeltaFloat
# coding: utf-8
class DeltaFloat(float):
def __new__(cls, value, delta=0.0001):
self = float.__new__(cls, value)
self.delta = delta
return self
def __eq__(self, other):
x = float(self)
@jsbueno
jsbueno / gist:07a3dfad97fc87c4683c
Created March 18, 2015 18:06
Simple iterator implementing a "back" method
class BackIterator(object):
def __init__(self, iterator):
self.current_index = 0
self.max_index = 0
self.previous_items = []
self.iterator = iterator
def __iter__(self):
return self
@jsbueno
jsbueno / simpleclass.py
Created March 19, 2015 18:59
"simpleclass" - namedtuple like factory for mutable objects
def simpleclass(name, attributes, **kw):
if isinstance(attributes, str):
attributes = attributes.split()
def __init__(self, *args, **kw):
attrs = dict(zip(self.__slots__, args))
attrs.update(kw)
for item in attrs.items():
setattr(self, *item)
return type(name, (object,), dict(__init__=__init__, __slots__= attributes))
rt = (lambda *args, **kw:((kw.update(dict(args))), ((type("ReturnType", (object,), dict(__slots__= [i1[0] for i1 in args] if args else list(kw.keys()) ,__getitem__=(lambda s, i:getattr(s, s.__slots__[i])), __setattr__=(lambda s, k, v: object.__setattr__(s, k ,v) if k in kw and isinstance(v, type(kw[k])) else setattr(s, getattr(s, k), None) ), __init__=(lambda s, **kw1:any(setattr(s,k1, v1) for k1, v1 in kw1.items()) or None), __repr__=(lambda s: "ReturnType({})".format(", ".join("{}={}".format(k2, repr(getattr(s, k2))) for k2 in s.__slots__) )) )))(**kw)))[1])
"""
####
# Usage:
>>> test = rt(a=1, b="blah", c=open("/dev/null"))
>>> print(test)
# Or, if you need to preserve, sequence order:
@jsbueno
jsbueno / autocopyproxy.py
Created May 22, 2015 19:37
a proxy wrapper for objects that lazily creates object copies on simple attribution of the object to other variables.
# copyright Joao S. O. Bueno (2015)
# License: # SVP write me if you intend to reuse stuff here for anything but mayhem
# There is an LGPL with lazyobjects based on this idea for proxy at
# bitbucket.org/jsbueno/metapython [lazy_decorator.py]
# NB: although there is support for inspecting Frames - this works only
# for global variables
# working for Python2 - for python3 onlye the metaclass usage should need to be changed
@jsbueno
jsbueno / linkedlist.py
Created July 18, 2015 04:02
Linked List implementation in Python2/3
# coding: utf-8
from __future__ import print_function
import sys
try:
from collections.abc import MutableSequence
except ImportError:
from collections import MutableSequence
@jsbueno
jsbueno / nonlocals.py
Created December 8, 2015 14:33
File sketch to implement a "nonlocals()" call in Python 3.x (analog to "globals()" and "locals()" )
import sys
from collections.abc import MutableMapping
class DictFilteredView(MutableMapping):
def __init__(self, viewed, allowed):
self.viewed = viewed
self.allowed = set(allowed)
def __getitem__(self, item):
if not item in self.allowed:
raise KeyError(str(item))
@jsbueno
jsbueno / dictdispatcher.py
Created April 9, 2013 02:30
Dict Dispatcher
class Renderer:
def __init__(self, entity):
self._entity = entity
def _expression(self):
return (type(self._entity))
_dispatch_table = {}
@jsbueno
jsbueno / cache.py
Last active December 21, 2015 08:59
def cache_page(*dec_args, **dec_kwargs):
cache_timeout = dec_args[0] if dec_args else None
cache_alias = dec_kwargs.pop('cache', None)
key_prefix = dec_kwargs.pop('key_prefix', '')
def decorator(func):
def wrapped(*func_args, **func_kwargs):
request = func_args[0]
cache_prefix = u'{}-{}-{}'.format(
key_prefix,
@jsbueno
jsbueno / life.py
Created February 20, 2016 06:47
Game of Life (Python + Pygame)
# coding: utf-8
import pygame
import random
rr = random.randrange
SIZE = 800, 600
cellsize = 20
try: