Created
September 3, 2016 03:29
-
-
Save khaotik/0a31802566afeb4b0addd2b1ea1ec68f to your computer and use it in GitHub Desktop.
Random small and useful utilities for python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
A collection of small python snippets that help code looking better | |
''' | |
class given(object): | |
''' | |
make a closure with local variables using with statement | |
usage example: | |
>>> a=10 | |
>>> with given(a=5, b=4): | |
... print(a+b) | |
9 | |
>>> a | |
10 | |
>>> b | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
NameError: name 'b' is not defined | |
''' | |
def __init__(self, **kwargs_): | |
self.vals = kwargs_ | |
def __enter__(self): | |
import inspect | |
self.loc = inspect.currentframe().f_back.f_locals | |
_lockeys = set(self.loc.keys()) | |
_vals = set(self.vals.keys()) | |
self.new_vals = _vals.difference(_lockeys) | |
self.backup_vals = {k:self.loc[k] for k in _vals.intersection(_lockeys)} | |
self.loc.update(self.vals) | |
def __exit__(self, excp_type_, excp_val_, traceback_ ): | |
if excp_type_: | |
raise excp_type_(excp_val_).with_traceback(traceback_) | |
for k in self.new_vals: | |
del self.loc[k] | |
self.loc.update( self.backup_vals ) | |
class Indexer(object): | |
''' | |
Creates slices using python's builtin slicing grammar | |
To use, call from the singleton instance of this class: idx | |
example usage: | |
>>> idx[5] | |
5 | |
>>> idx[1,2:3,:-2:2,'key'] | |
(1, slice(2, 3, None), slice(None, -2, 2), 'key') | |
''' | |
def __getitem__(self,*args_): | |
return args_[0] | |
idx = Indexer() | |
class refine(object): | |
''' | |
Apply a serie of filters, yields successively filtered objects | |
Args: | |
filters_: iterable of (function->bool | None) | |
oil_: iterable elements to be refined | |
Yields: | |
(idx, elem) | |
idx: the number of filter function that first returns True on elem | |
Examples: | |
TODO | |
''' | |
def __init__(self, filters_, oil_): | |
self.filters = filters_ | |
self.oil = oil_ | |
def __iter__(self): | |
for elem in self.oil: | |
for i,f in enumerate(self.filters): | |
if f(elem): | |
yield (i,elem) | |
break | |
def is2n(n_): | |
'''returns whether integer n_ is power of 2''' | |
return len(set(bin(n_-1)[2:])) == 1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment