Update factory init injections example and picture

This commit is contained in:
Roman Mogylatov 2020-08-30 14:32:00 -04:00
parent 7da1a38718
commit a606baa637
4 changed files with 32 additions and 41 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

View File

@ -24,18 +24,11 @@ injected following these rules:
+ Keyword context arguments have the priority over the ``Factory`` keyword dependencies with the
same name.
For example, if injectable value of injection is a :py:class:`Factory`, it
will provide new one instance (as a result of its call) every time, when
injection needs to be done.
Example below is a little bit more complicated. It shows how to create
:py:class:`Factory` of particular class with ``__init__()`` injections which
injectable values are also provided by another factories:
.. image:: /images/providers/factory_init_injections.png
.. image:: images/factory_init_injections.png
.. literalinclude:: ../../examples/providers/factory_init_injections.py
:language: python
:lines: 3-
Factory providers and building complex object graphs
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

View File

@ -1,39 +1,37 @@
"""`Factory` providers init injections example."""
import collections
import dependency_injector.providers as providers
from dependency_injector import providers
CreditCard = collections.namedtuple('CreditCard', [])
Photo = collections.namedtuple('Photo', [])
User = collections.namedtuple('User', ['uid', 'main_photo', 'credit_card'])
# User, Photo and CreditCard factories:
credit_cards_factory = providers.Factory(CreditCard)
photos_factory = providers.Factory(Photo)
users_factory = providers.Factory(User,
main_photo=photos_factory,
credit_card=credit_cards_factory)
# Creating several User objects:
user1 = users_factory(1)
# Same as: user1 = User(1,
# main_photo=Photo(),
# credit_card=CreditCard())
user2 = users_factory(2)
# Same as: user2 = User(2,
# main_photo=Photo(),
# credit_card=CreditCard())
class Photo:
...
# Context keyword arguments have priority on keyword argument injections:
main_photo = Photo()
credit_card = CreditCard()
class User:
user3 = users_factory(3,
main_photo=main_photo,
credit_card=credit_card)
# Same as: user3 = User(3,
# main_photo=main_photo,
# credit_card=credit_card)
def __init__(self, uid: int, main_photo: Photo):
self.uid = uid
self.main_photo = main_photo
photo_factory = providers.Factory(Photo)
user_factory = providers.Factory(
User,
main_photo=photo_factory,
)
if __name__ == '__main__':
user1 = user_factory(1)
# Same as: # user1 = User(1, main_photo=Photo())
user2 = user_factory(2)
# Same as: # user2 = User(2, main_photo=Photo())
# Context keyword arguments have a priority:
another_photo = Photo()
user3 = user_factory(
uid=3,
main_photo=another_photo,
)
# Same as: # user3 = User(uid=3, main_photo=another_photo)