Skip to content

Commit

Permalink
Add support for classes in autoparams (ivankorobkov#59)
Browse files Browse the repository at this point in the history
  • Loading branch information
dbalabka committed May 15, 2020
1 parent 57dc670 commit 1528dd4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 4 additions & 1 deletion inject/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,10 @@ def sign_up(name, email, cache: RedisCache, db: DbInterface):
pass
"""
def autoparams_decorator(fn: Callable[..., T]) -> Callable[..., T]:
types = get_type_hints(fn)
if inspect.isclass(fn):
types = get_type_hints(fn.__init__)
else:
types = get_type_hints(fn)

# Skip the return annotation.
types = {name: typ for name, typ in types.items() if name != _RETURN}
Expand Down
19 changes: 19 additions & 0 deletions test/test_functional.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from unittest import TestCase

import inject
from inject import autoparams


class TestFunctional(TestCase):
Expand Down Expand Up @@ -57,3 +58,21 @@ def config(binder):
assert type(inject.instance(DataFrame)) is DataFrame
# There should not be an error when we fetch created instance
assert type(inject.instance(DataFrame)) is DataFrame

def test_class_support_in_autoparams_programmaticaly(self):
class AnotherClass:
pass

class SomeClass:
def __init__(self, another_object: AnotherClass):
self.another_object = another_object

def config(binder):
binder.bind_to_constructor(SomeClass, autoparams()(SomeClass))
binder.bind_to_constructor(AnotherClass, autoparams()(AnotherClass))

inject.configure(config)

some_object = inject.instance(SomeClass)
assert type(some_object) is SomeClass
assert type(some_object.another_object) is AnotherClass

0 comments on commit 1528dd4

Please sign in to comment.