Skip to content
This repository has been archived by the owner on Jan 13, 2023. It is now read-only.

Commit

Permalink
Enable kwargify on class constructors
Browse files Browse the repository at this point in the history
Kwargify now can take also classes, in that case it pulls the __init__ for analysis but it then calls the class directly.
  • Loading branch information
Milan Falešník committed Feb 2, 2016
1 parent 4a52ae1 commit ba6767c
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
18 changes: 11 additions & 7 deletions kwargify.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@
import inspect


def kwargify(wrapped):
_method = hasattr(wrapped, "im_func") or type(wrapped).__name__ == "method"
def kwargify(a_callable):
call_target = a_callable
if inspect.isclass(a_callable):
# Pull the __init__
a_callable = a_callable.__init__
_method = hasattr(a_callable, "im_func") or type(a_callable).__name__ == "method"
_defaults = {}
argspec = inspect.getargspec(wrapped)
argspec = inspect.getargspec(a_callable)
if _method:
_args = argspec.args[1:]
else:
Expand All @@ -30,17 +34,17 @@ def wrapper(*args, **kwargs):
pass_args.append(_defaults[arg])
else:
raise TypeError("Required parameter {} not found in the context!".format(arg))
return wrapped(*pass_args)
return call_target(*pass_args)

# Doing the work of functools.wraps from python 3.2+
assigned = ('__module__', '__name__', '__qualname__', '__doc__', '__annotations__')
for attr in assigned:
try:
value = getattr(wrapped, attr)
value = getattr(a_callable, attr)
except AttributeError:
pass
else:
setattr(wrapper, attr, value)
vars(wrapper).update(vars(wrapped))
wrapper.__wrapped__ = wrapped
vars(wrapper).update(vars(a_callable))
wrapper.__wrapped__ = a_callable
return wrapper
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

setup(
name="kwargify",
version="2.0.1",
version="2.1.0",
author="Milan Falešník",
author_email="milan@falesnik.net",
description="Python function kwargifier",
Expand Down
12 changes: 12 additions & 0 deletions test_kwargify.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,3 +215,15 @@ def c(self, a, b=None):
assert result_1["a"] == result_2["a"] == 1
assert result_1["b"] == 2
assert result_2["b"] is None


def test_wrap_class_constructor():
class A(object):
def __init__(self, a, b=None):
self.a = a
self.b = b

cons = kwargify(A)
a = cons(a=1)
assert a.a == 1
assert a.b is None

0 comments on commit ba6767c

Please sign in to comment.