Skip to content

Instantly share code, notes, and snippets.

@c6401
Last active October 2, 2017 00:13
Show Gist options
  • Save c6401/55ef574fb84804a62eb271bd677a6935 to your computer and use it in GitHub Desktop.
Save c6401/55ef574fb84804a62eb271bd677a6935 to your computer and use it in GitHub Desktop.
Various python snippets
"""
The MIT License (MIT)
Copyright (c) 2016, Ruslan Zhenetl
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import re
import shelve
from collections import namedtuple, defaultdict
from datetime import datetime
from itertools import groupby
from operator import itemgetter
import click
import paramiko
from six.moves.urllib.parse import urlparse
class ObjectFab(object):
"""
Simple and dirty memoized class constructor for ipython notebook or
fast hacking.
>>> ObjectFab(x=1, y=2)
YXNamedTuple(y=2, x=1)
>>> ObjectFab('Point', x=1, y=2)
Point(y=2, x=1)
"""
instances = {}
def __new__(cls, _class_name=None, **kwargs):
name = (
_class_name or
''.join(k.capitalize() for k in kwargs.keys()) + 'NamedTuple'
)
return cls.instances.setdefault(
name, namedtuple(name, kwargs.keys())
)(**kwargs)
def parse_indented(text):
"""
>>> parse_indented('''
... a
... b
... ''')
[{'name': 'a', 'children': [{'name': 'b', 'children': []}]}]
"""
prepared_lines = (l.expandtabs() for l in text.splitlines() if l.strip())
grouped = groupby(prepared_lines, lambda s: len(s) - len(s.lstrip(' ')))
stack = [[]]
indents = [-1]
for indent, names in grouped:
while indent <= indents[-1]:
stack = stack[:-1]
indents.pop()
indents.append(indent)
stack[-1].extend({
'name': name.strip(),
'children': [],
} for name in names)
stack.append(stack[-1][-1]['children'])
return stack[0]
class shelve_cache(object):
"""
@shelve_cache
def my_heavy_function():
...
@shelve_cache('cache_file_name.shelve')
def my_heavy_function():
...
"""
def _set_func(self, func):
self.func = func
return self
def __new__(cls, arg):
instance = super(shelve_cache, cls).__new__(cls)
if callable(arg):
instance._set_func(arg)
name = 'cache_{}.shelve'.format(arg.__name__)
instance.cache = shelve.open(name)
return instance
else:
instance.cache = shelve.open(arg)
return instance._set_func
def __call__(self, *args, **kwargs):
key = self.make_key(*args, **kwargs)
if key in self.cache:
return self.cache[key][0]
result = self.func(*args, **kwargs)
self.cache[key] = result, datetime.now()
self.cache.sync()
return result
@staticmethod
def make_key(*args, **kwargs):
return str((args, kwargs))
def get_nested(dict_, path):
"""
>>> get_nested({'a': {'b': 1}}, ['a', 'b'])
1
"""
return reduce(lambda d, key: d[key], path, dict_)
def squash_dicts(dicts, **operations):
"""
>>> squash_dicts([{'a': {'c': 1}}, {'a': {'c': 2}, 'b': 3}], a__c=sum)
{'a': {'c': 3}, 'b': 3}
"""
result = dicts[0].copy()
for dict_ in dicts[1:]:
result.update(dict_)
for path_string, operation in operations.items():
path = path_string.split('__')
aggregated = operation(get_nested(d, path) for d in dicts)
get_nested(result, path[:-1])[path[-1]] = aggregated
return result
def group_by(iterable, key):
groups = {}
for item in iterable:
groups.setdefault(key(item), []).append(item)
return groups
def join(left, right, **conditions):
l_index = itemgetter(*conditions.keys())
r_index = itemgetter(*conditions.values())
right_indexed = {r_index(r): r for r in right}
return [dict(l, **right_indexed[l_index(l)]) for l in left]
@contextmanager
def sftp_open(url_string, mode='r', key_filename=None, timeout=None):
"""Implements interface similar to __builtin__.open
:param str path: 'ssh://{user}:{password}@{host}/{path}'
:raises IOError
>>> with sftp_open('ssh://user:password@host/path/filename.ext') as f:
>>> content = f.read()
...
>>> with sftp_open('ssh://user:password@host/path/filename.ext', 'w') as f:
>>> f.write('content')
...
"""
url = urlparse(url_string if '//' in url_string else '//' + url_string)
with paramiko.SSHClient() as ssh:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(
hostname=url.hostname, port=url.port, username=url.username,
password=url.password, key_filename=key_filename, timeout=timeout,
)
with ssh.open_sftp() as sftp:
with sftp.file(url.path, mode) as f:
yield f
def ascii_table(model_list):
table = [model_list[0].keys()] + [m.values() for m in model_list]
lengths = map(lambda col: max(len(str(cell)) for cell in col), zip(*table))
template = ' | '.join('{{:<{}}}'.format(l) for l in lengths)
return '\n'.join(template.format(*r) for r in table)
class InspectedFunc(object):
re_params = re.compile('[ ]*:param (\w+): (.+)')
def __init__(self, func):
self.varnames = func.__code__.co_varnames[:func.__code__.co_argcount]
self.descriptions = dict(self.re_params.findall(func.__doc__ or ''))
self.defaults = dict(zip(
reversed(self.varnames), reversed(func.__defaults__ or [])
))
class Autocommand(object):
def __init__(self, group, config={}):
"""
@click.group()
def cli(): pass
autocommand = Autocommand(cli)
@autocommand
def(param_name: type):
'''command help
:param param_name: help text
'''
"""
self.group = group
self.config = defaultdict(dict)
self.config.update(config)
def __call__(self, command_name=None):
def register(func):
inspected = InspectedFunc(func)
defaults = inspected.defaults.copy()
defaults.update(self.config['defaults'].get(func.__name__, {}))
used = set()
for name in inspected.varnames:
chars = name[0] + name.capitalize()
char = next((c for c in chars if c not in used), None)
used.add(char)
click.option(
'-' + char,
'--' + name,
default=defaults.get(name),
type=func.__annotations__.get(name),
help=inspected.descriptions.get(name, ''),
prompt=name not in defaults,
)(func)
self.group.command(
self.config['command_names'].get(func.__name__) or command_name
)(func)
return func
return register
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment