Two question about python-inject.

89 views
Skip to first unread message

Krystian Kichewko

unread,
Feb 21, 2014, 8:59:40 AM2/21/14
to python...@googlegroups.com
Hello Ivan!

I have two questions about python-inject:

The first one is: When does the inject happen? Is it happening when I create a new of a class? Or is it injected when class itself is created?

Second one would be:
In the documentation you mention that custom providers can be used to create custom scopes: "In python-inject write custom providers which can be thread-local, request-local, etc.".
I would like to use something similar to Spring's prototype scope? How can I achieve this? Is it enough to use binder.bind_to_provider and pass a factory method as a second argument (e.g. we have a class A and we do: binder.bind_to_provider(A, A) )?

Thanks for an awesome library.

Krystian Kichewko

Ivan Korobkov

unread,
Feb 21, 2014, 9:20:45 AM2/21/14
to python...@googlegroups.com
Hello!

1. Injection happens when you actually access a class attribute (inject.attr), or when you call inject.instance.
python-inject uses one static injector to get dependencies. Some think it cannot be called DI because you
request dependencies, not inject them. In my opinion, it's a matter of terminology.

2. You don't need a prototype scope. Just create any object the way you like. You don't need binder.bind_to_provider(A, A)
For example:

# Inject a queue into an email
class Email(object):
    mailer_queue = inject.attr(MailerQueue)

    def __init__(self, to, text):
        self.to = to
        self.text = text

    def send(self):
        self.mailer_queue.send(self)

# Somewhere configure the injector with a MailerQueue binding
inject.configure(lambda: binder.bind(MailerQueue, someQueue))

# Create Email as a normal class (no need for a prototype scope)
# MailerQueue is injected when you access it.
email = Email("te...@test.com")
email.send()


Spring and guice replace your constructors and manage your object graph. 
Guice even states it the new "new" in Java (and I like it a lot in Java). 
python-inject is simpler. It just injects dependencies.
Feel free to see the source code, it's less then 300 lines.


--
You received this message because you are subscribed to the Google Groups "python-inject" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python-injec...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.



--
Ivan Korobkov
ivan.k...@gmail.com

Krystian Kichewko

unread,
Feb 21, 2014, 4:11:29 PM2/21/14
to python...@googlegroups.com
Hi Ivan!

Thank you for your answers. This clears my confusion.

Krystian Kichewko
Reply all
Reply to author
Forward
0 new messages