public
Last active

  • Download Gist
magicbind.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
import functools
import inspect
import types
from itertools import izip_longest
 
 
class MagicBind(object):
""" Bind specific arguments of object methods for the lazy.
 
A quick example of binding a requests session to an URL::
 
from requests.sessions import Session
my_session = Session()
google_session = MagicBind(my_session, url='http://google.com')
google_session.get()
 
>>> class Test(object):
... def no_args(self):
... return self
... def two_positional(self, x, y):
... return x, y
... def three_positional(self, x, y, z):
... return x, y, z
... def defaults(self, x=1, y=2, z=3):
... return x, y, z
... def args_kwargs(self, x, y, *args, **kwargs):
... return x, y, args, list(sorted(kwargs.items()))
... def only_args_kwargs(self, *args, **kwargs):
... return args, list(sorted(kwargs.items()))
 
>>> t = Test()
>>> mb = MagicBind(t, x=10)
>>> mb.no_args() is t
True
>>> mb.two_positional(20)
(10, 20)
>>> mb.three_positional(20, 30)
(10, 20, 30)
>>> mb.defaults(20)
(10, 20, 3)
>>> mb.defaults()
(10, 2, 3)
>>> mb.defaults(y=20)
(10, 20, 3)
>>> mb.args_kwargs(20, 30, 40, z=50, w=60)
(10, 20, (30, 40), [('w', 60), ('z', 50)])
>>> mb.only_args_kwargs()
((), [])
>>> mb.args_kwargs(20, 30, x=50, w=60) # doctest:+IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
TypeError:
>>> mb.only_args_kwargs(20, 30, 40, z=50, w=60)
((20, 30, 40), [('w', 60), ('z', 50)])
>>> mb.only_args_kwargs(10, 20, x=30, y=40)
((10, 20), [('x', 30), ('y', 40)])
 
"""
def __init__(self, obj, **kwargs):
self._obj = obj
self._update_with = kwargs
 
def __getattr__(self, name):
func = getattr(self._obj, name)
if not callable(func):
return func
args, varargs, keywords, defaults = inspect.getargspec(func)
if defaults is None:
defaults = []
if isinstance(func, types.MethodType):
args = args[1:]
r_avrgs, r_defaults = reversed(args), reversed(defaults)
sentinel = object()
new_args, new_defaults = [], []
for a, d in reversed(list(
izip_longest(r_avrgs, r_defaults, fillvalue=sentinel)
)):
if a not in self._update_with:
new_args.append(a)
if d is not sentinel:
new_defaults.append(d)
new_args_count = len(new_args)
if varargs is not None:
new_args.append(varargs)
if keywords is not None:
new_args.append(keywords)
 
# clone the func and change args
if isinstance(func, types.MethodType):
code = func.im_func.func_code
else:
code = func.func_code
f_code = types.CodeType(
new_args_count,
code.co_nlocals,
code.co_stacksize,
code.co_flags,
code.co_code,
code.co_consts,
code.co_names,
tuple(new_args),
code.co_filename,
code.co_name,
code.co_firstlineno,
code.co_lnotab
)
f_func = types.FunctionType(f_code, {}, None, tuple(new_defaults))
 
@functools.wraps(func)
def wrapper(*positional, **named):
call_args = inspect.getcallargs(f_func, *positional, **named)
actual_args = []
for arg in args:
actual_args.append(
call_args.get(arg, self._update_with.get(arg))
)
if varargs is not None:
actual_args += call_args[varargs]
actual_kwargs = {}
if keywords is not None:
actual_kwargs = call_args[keywords]
return func(*actual_args, **actual_kwargs)
setattr(self, name, wrapper)
return wrapper

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.