alecthomas/injector — pull request #14 by jstasiak (2013-02-08 13:08:13+00:00)
Title: Prototype member injection API

This pull request is not meant to be merged at the moment but rather start some discussion.

The reason why I'd like to see some form of member injection is that I find myself writing a lot of code like this:

```python
class A(object):
@inject(asd = Asd, qwe = Qwe, zxc = Zxc)
def __init__(self, asd, qwe, zxc):
self.asd = asd
self.qwe = qwe
self.zxc = zxc
```

or
```python
class A(object):
@inject(asd = Asd, qwe = Qwe, zxc = Zxc)
def __init__(self, **kwargs):
for key in ('asd', 'qwe' ,'zxc'):
setattr(self, key, kwargs.pop(key))
assert not kwargs
```

You could theoretically make it without repeating the names by

```python
class A(object):
@inject(asd = Asd, qwe = Qwe, zxc = Zxc)
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
```

but it would just silently copy any kwarg you pass it, even kwarg that you don't want to accept there.

Member injection would make it slightly better looking and easier to use. It's also safer than accept-any-kwargs-and-copy-to-self solution.

```python
class A(object):
asd = inject(Asd)
qwe = inject(Qwe)
zxc = inject(Zxc)
```

I'd like to discuss possible API for member injection, that's why I didn't provide any implementation yet.