<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Tomasz Wąsiński's Blog]]></title><description><![CDATA[Tomasz Wąsiński's Blog]]></description><link>https://blog.wasinski.dev</link><generator>RSS for Node</generator><lastBuildDate>Sun, 08 Nov 2026 11:24:16 GMT</lastBuildDate><atom:link href="https://blog.wasinski.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Comparison of Dependency Injection Libraries in Python, and my favorite one]]></title><description><![CDATA[In one of my last posts, I gave an introduction to DI pattern: why it is crucial for software projects & how it differs from Service Locator patterns. Long…]]></description><link>https://blog.wasinski.dev/comparison-of-dependency-injection-libraries-in-python</link><guid isPermaLink="true">https://blog.wasinski.dev/comparison-of-dependency-injection-libraries-in-python</guid><category><![CDATA[Python]]></category><category><![CDATA[dependency injection]]></category><category><![CDATA[design principles]]></category><dc:creator><![CDATA[Tomasz Wąsiński]]></dc:creator><pubDate>Fri, 18 Dec 2020 12:51:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1637931078748/xQAssnhHX.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-about-dependency-injection">About Dependency Injection</h2>
<p><a target="_blank" href="/dependency-injection-service-locator-1">In one of my last posts, I gave an introduction to DI pattern</a>: why it is crucial for software projects &amp; how it differs from Service Locator patterns. Long story short using DI supports <em>Low Coupling &amp; High Cohesion</em> in turn gives us great testability and configurability.</p>
<h2 id="heading-short-overview-of-available-di-libraries-in-python">Short overview of available DI libraries in Python</h2>
<p>DI is not a commonly used concept in the Python community, actually often it's quite neglected, because "Python is not Java", obviously, but this does not mean that we should not strive to write good, testable code, and that's the reason why we should use DI.
The popularity of Django, which suggests in its documentation a design that does not support any Inversion of Control also does not help with promoting good practices.
Lately, FastAPI gain popularity, and it's the first (to my knowledge) web framework which supports native Dependency Injection
Because of all of these reasons, there are just a few DI containers available, some of them do not even hold the definition of a good container.</p>
<p><img src="/in-posts/post-4/globalcontainervsinstanciated.png" alt="Container which requires instantiation vs globally configured container" /></p>
<h3 id="heading-what-describes-a-good-di-container">What describes a good DI container</h3>
<p>A good DI container:</p>
<ul>
<li><strong>must not</strong> be a Service Locator, and that's easier to get as one might think, just go back to my previous post about this topic</li>
<li><strong>must not</strong> be configurable globally (as a globally available instance), because it introduces problems with the reconfiguration</li>
<li><strong>must</strong> support <em>shared dependencies</em>, so we wouldn't need to exploit the Singleton Pattern</li>
<li><strong>must</strong> support use of <em>profiles</em>, so we can configure it accordingly on different environments</li>
<li><strong>should</strong> support the Decorator Pattern</li>
</ul>
<p><img src="/in-posts/post-4/containerwithsharedinstancebehavior.png" alt="Container with shared instance behavior explained" /></p>
<h3 id="heading-overview-of-available-solutions">Overview of available solutions</h3>
<ul>
<li><p>https://github.com/ivankorobkov/python-inject
  disqualified because it uses globally available configuration, and descriptors to pull instances from it, which makes it more of a Service Locator. It also uses Singletons as the default scope which is even worse.</p>
</li>
<li><p>https://github.com/google/pinject
  from Google. Feels highly outdated and so it is, as the documentation is still written for Python2. Also, it uses Singletons as default, so even though the container is an instance created "in place" it still returns the same instances again and again. It does not support any reconfiguration solutions for tests.</p>
</li>
<li><p>https://github.com/alecthomas/injector
  well... I can't tell anything <em>very</em> bad about it, but nothing good either. My problem with it is its interface, which for me isn't very pleasant to use.</p>
</li>
<li><p>http://python-dependency-injector.ets-labs.org/introduction/di_in_python.html
  Very good library, actively supported, it's the only drawback from my point of view is the boilerplate which is necessary to create even a small app with it. But besides that it has many pros: support for multiple types of scopes (default is shared instance, but it includes also very interesting <code>Configuration</code> or <code>Resource</code>); it allows defining small containers, no global configuration, supports modularization; it allows to override the configuration for e.g. tests purpose; provides <code>wire</code> mechanism to integrate with popular frameworks, even Django. A really good choice!</p>
</li>
</ul>
<h2 id="heading-the-winner-dependencies-aka-injector">The winner - <em>dependencies</em> aka Injector</h2>
<p>My personal winner is https://github.com/proofit404/dependencies which I'm used to cal <strong>Injector</strong>, because that's the name of the main class.</p>
<h3 id="heading-fundamentals">Fundamentals</h3>
<ul>
<li>dependencies are matched by <code>__init__</code> parameter names</li>
<li>container returns always a fresh instance when called for one</li>
<li>it uses <em>shared instance</em> scope by default, and it's the only available scope out of the box.</li>
</ul>
<p>These simple mechanisms allowed the author of the library to create a really nice abstraction over the configuration of the container and its internals. Actually, everything is very nicely encapsulated, and the user must remember about only these 3 points.</p>
<p>One might ask why <em>parameter names</em> and not types as it usually is in other libraries?
The author justifies it by superior readability of his approach which would not be possible with the usage of types:</p>
<pre><code class="lang-Python"><span class="hljs-keyword">from</span> typing <span class="hljs-keyword">import</span> List
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Container</span>:</span>
    List = list
</code></pre>
<p><code>Container.List</code> is just a string under the hood. Well, it's really hard to argue with the author, because this design really is pretty, just check it below!</p>
<h3 id="heading-in-practice">In practice</h3>
<p>This is how the code can look like in practice</p>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomerFeedContainer</span>(<span class="hljs-params">Injector</span>):</span>
    bml_client = BMLAPIClient
    drunken_water_info_provider = BMLDrunkenWaterInfoProvider

    <span class="hljs-comment"># entry points</span>
    query_entry = CustomerFeedQueryEntry

    <span class="hljs-comment"># queries</span>
    GetDrunkenWaterDataForCustomerQuery = GetDrunkenWaterDataForCustomerHandler


<span class="hljs-meta">@dataclass</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomerFeedQueryEntry</span>(<span class="hljs-params">InjectorQueryEntry</span>):</span>
    GetDrunkenWaterDataForCustomerQuery: GetDrunkenWaterDataForCustomerHandler

<span class="hljs-meta">@dataclass</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BMLDrunkenWaterInfoProvider</span>:</span>
    bml_client: BMLAPIClient
    [...]

<span class="hljs-meta">@dataclass</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GetDrunkenWaterDataForCustomerHandler</span>(<span class="hljs-params">
    QueryHandler[GetDrunkenWaterDataForCustomerQuery, DrunkenWaterView]
</span>):</span>
    drunken_water_info_provider: DrunkenWaterInfoProvider
    [...]
</code></pre>
<p><code>CustomerFeedContainer</code> stores the configuration, a call to it's <code>getattr</code> method will return a built instance of one of the defined dependencies. Let's say we want to get an instance of <code>BMLDrunkenWaterInfoProvider</code> which uses <code>BMLAPIClient</code> underneath. We just do:</p>
<pre><code class="lang-Python">provider_instance = CustomerFeedContainer.drunken_water_info_provider
</code></pre>
<p>what happens under the hood is the match of <code>CustomerFeedContainer.bml_client</code> to <code>BMLDrunkenWaterInfoProvider.__init__(self, bml_client)</code>, which allows us to provide different implementations of <code>BMLAPIClient</code> as long as it matches the kwarg name and the interface of course.</p>
<h3 id="heading-pros">Pros</h3>
<ul>
<li>very easy to use, thanks to it's design the DI configuration is very simple to do</li>
<li>it allows to override the configuration for tests with the use of <code>Injector()</code> or previously <code>Injector.let()</code></li>
<li>it does introduce to our code any hard dependencies like decorators or descriptors as other libraries usually do. We only need to watch out for <em>override</em> usage in tests, but that can be abstracted out too.</li>
<li>concrete <em>composition root</em> in the form of <code>Injector</code> class - supports modularization</li>
<li>nice documentation</li>
</ul>
<h3 id="heading-cons">Cons</h3>
<ul>
<li>its simplicity is also a con, as it does not provide too many features. If you need a Singleton you have to think about how to achieve that, but that's a pro too if you'd ask me - thinking before doing is good</li>
<li>does not provide any integration for frameworks</li>
<li>returned instances aren't typed</li>
<li>only one maintainer, but very active and supportive</li>
</ul>
<h3 id="heading-patterns">Patterns</h3>
<h4 id="heading-composition-root">Composition root</h4>
<p>When we do not have a globally stored configuration/container as in one of the fore-mentioned libraries we should strive for small purposeful containers which will be our composition roots for e.g. modules of our application. A good idea is also to separate the business logic dependencies from the infrastructural ones and couple them together somewhere at the root of our application.</p>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DI</span>(<span class="hljs-params">Injector</span>):</span>
    db_session = DBSession

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Config</span>(<span class="hljs-params">Injector</span>):</span>
    db_uri = <span class="hljs-string">"postgres://localhost"</span>

DI.db_session  <span class="hljs-comment"># raises DepencencyError</span>
(DI &amp; Config).db_session  <span class="hljs-comment"># OK!</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DIAndConfig</span>(<span class="hljs-params">DI, Config</span>):</span> ...

DIAndConfig.db_session  <span class="hljs-comment"># OK!</span>
</code></pre>
<h4 id="heading-too-many-dependencies-anti-pattern"><em>too many dependencies</em> anti-pattern</h4>
<p>It's not hard to predict that because the container builds always a fresh instance, then we should care about having a small number of dependencies in the classes. What it comes down to in practice is having specific <code>ApplicationService</code>s or as I prefer <code>CommandHandler</code>s which do one thing.</p>
<h4 id="heading-container-encapsulation">Container encapsulation</h4>
<p>As I wrote in one of my last posts injecting the container is a very bad thing to do, because it becomes more of a service locator than a DI solution. However, depending on how our app's architecture is layered, or how we do the assembly of our whole app, for example, based on the framework we're using for web, or when our app is composed of modules we might need to "call" our container from a client class.
My solution to that problem is encapsulating the container behind a nice abstraction:</p>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Module</span>(<span class="hljs-params">ABC</span>):</span>
    <span class="hljs-string">"""
    Module encapsulates a module, providing only 2 actions:
    handle - for commands/queries,
    override - for overriding module's setup, particularly dependencies.
    """</span>

<span class="hljs-meta">    @abstractmethod</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">handle</span>(<span class="hljs-params">self, action: Union[Query, Command]</span>) -&gt; Any:</span>
        <span class="hljs-keyword">pass</span>

<span class="hljs-meta">    @abstractmethod</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">override</span>(<span class="hljs-params">self: TMod, **dependencies: Any</span>) -&gt; TMod:</span>
        <span class="hljs-keyword">pass</span>


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">InjectorModule</span>(<span class="hljs-params">Module</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, container: Type[Injector]</span>) -&gt; <span class="hljs-keyword">None</span>:</span>
        self.container = container

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">handle</span>(<span class="hljs-params">self, action: Union[Query, Command]</span>) -&gt; Any:</span>
        <span class="hljs-keyword">if</span> isinstance(action, Query):
            <span class="hljs-keyword">return</span> cast(InjectorQueryEntry, self.container.query_entry).handle(action)
        <span class="hljs-keyword">if</span> isinstance(action, Command):
            <span class="hljs-keyword">return</span> cast(InjectorCommandEntry, self.container.command_entry).handle(action)
        <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"Action must be a Command or Query"</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">override</span>(<span class="hljs-params">self: TInjectorMod, **dependencies: Any</span>) -&gt; TInjectorMod:</span>
        <span class="hljs-keyword">return</span> self.__class__(self.container.let(**dependencies))

<span class="hljs-meta">    @classmethod</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">new</span>(<span class="hljs-params">cls: Type[TInjectorMod], container: Type[Injector]</span>) -&gt; TInjectorMod:</span>
        <span class="hljs-keyword">return</span> cls(container)


CustomerActivities = InjectorModule.new(CustomerActivitiesContainer)
</code></pre>
<p>That way a <code>Controller</code> element of the app can have direct access only to a <code>Module</code> with a very specific and small interface, and not the whole <code>Injector</code> container.</p>
<p>Encapsulating the container is also crucial from the point of view of its exchange to a different solution someday. It mitigates one of the cons that I mentioned before: it can hide the calls to the override mechanism. </p>
<h4 id="heading-singletons-or-long-living-instances">Singletons or long-living instances</h4>
<p>Sometimes we might want to use the same instance (or rather have it returned by the Injector) through many calls to the DI container, an example could be the same connection to a database. There are some ways to deal with that.</p>
<p>We can create the instance out of the scope of the container and then pass it as a keyword argument using the <em>override</em> mechanism:</p>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DI</span>(<span class="hljs-params">Injector</span>):</span>
    singleton = <span class="hljs-literal">None</span>

a_singleton = SomeService()

di = DI.let(singleton=a_singleton)

<span class="hljs-keyword">assert</span> di.singleton <span class="hljs-keyword">is</span> di.singleton <span class="hljs-keyword">is</span> a_singleton
</code></pre>
<p>Or we can use "the real" Singleton Pattern:</p>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Singleton</span>(<span class="hljs-params">type</span>):</span>
    _instances = {}
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span>(<span class="hljs-params">cls, *args, **kwargs</span>):</span>
        <span class="hljs-keyword">if</span> cls <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        <span class="hljs-keyword">return</span> cls._instances[cls]

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DBSession</span>(<span class="hljs-params">metaclass=Singleton</span>):</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, db_uri</span>):</span>
        self.db_uri = db_uri
        self._is_connected = <span class="hljs-literal">False</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">connect</span>(<span class="hljs-params">self</span>):</span>
        self._is_connected = <span class="hljs-literal">True</span>

<span class="hljs-meta">    @property</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_connected</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self._is_connected

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DI</span>(<span class="hljs-params">Injector</span>):</span>
    db_session = DBSession
    db_uri = <span class="hljs-string">"postgres://localhost"</span>

DI.db_session.connect()
<span class="hljs-keyword">assert</span> DI.db_session.is_connected
</code></pre>
<p>In one of my projects I used such a nice piece of code to have the <code>UnitOfWork</code> live through several calls to the <code>Module</code> which holds it - to be able to check the emitted <code>DomainEvents</code> (out of scope here)</p>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FakeInjectorModule</span>(<span class="hljs-params">InjectorModule</span>):</span>
    <span class="hljs-string">"""
    A Module that uses the same UoW instance, providing a scoped Singleton
    object. This allows to have:
    - persistence in FakeRepositories
    - checking if UoW was committed
    - checking published Events
    """</span>

    _unit_of_work: FakeUnitOfWork

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, container: Injector</span>) -&gt; <span class="hljs-keyword">None</span>:</span>
        self._unit_of_work = container.unit_of_work
        self.container = container.let(unit_of_work=self._unit_of_work)

<span class="hljs-meta">    @property</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">unit_of_work</span>(<span class="hljs-params">self</span>) -&gt; FakeUnitOfWork:</span>
        <span class="hljs-keyword">return</span> self._unit_of_work
</code></pre>
<p>Of course, I think that building the instance outside of the container is a much better, reliable, and predictable approach than using the Singleton. It's common to forget that we are using a Singleton...</p>
<h4 id="heading-profiles">Profiles</h4>
<p>To configure dynamically the dependencies, for example, based on environmental variables or something you can use a Factory-like custom provider and <code>@value</code> decorator. Below I used string <code>profiles</code>, but it does not matter where the <code>profiles</code> come from, it can be envs</p>
<pre><code class="lang-Python"><span class="hljs-keyword">from</span> dependencies <span class="hljs-keyword">import</span> Injector, this, value
<span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> dataclass


<span class="hljs-meta">@dataclass</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DB</span>:</span>
    name: str


<span class="hljs-meta">@dataclass</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DBProvider</span>:</span>
    profiles: str

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">provide</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">if</span> <span class="hljs-string">"dev"</span> <span class="hljs-keyword">in</span> self.profiles:
            <span class="hljs-keyword">return</span> DB(<span class="hljs-string">"DEV DB"</span>)
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> DB(<span class="hljs-string">"PROD DB"</span>)


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DI</span>(<span class="hljs-params">Injector</span>):</span>
    db = this.db_provider

<span class="hljs-meta">    @value</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">db_provider</span>(<span class="hljs-params">profiles: str = <span class="hljs-string">""</span></span>):</span>
        <span class="hljs-keyword">return</span> DBProvider(profiles).provide()


dev_db = DI.db
prod_db = DI.let(profiles=<span class="hljs-string">"dev"</span>).db
</code></pre>
<h3 id="heading-upcoming-enhancements">Upcoming enhancements</h3>
<h4 id="heading-easy-decorator-pattern-support">easy Decorator Pattern support</h4>
<pre><code class="lang-Python"><span class="hljs-keyword">from</span> dependencies <span class="hljs-keyword">import</span> Injector, decorate


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CommandLoggerHandler</span>(<span class="hljs-params">CommandHandler</span>):</span>
    logger: Logger
    handler: CommandHandler

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">handle</span>(<span class="hljs-params">cmd: Command</span>):</span>
        self.logger.log(<span class="hljs-string">f"handle command <span class="hljs-subst">{cmd}</span>"</span>)
        <span class="hljs-keyword">return</span> self.handler(cmd)


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomerActivitiesContainer</span>(<span class="hljs-params">Injector</span>):</span>
    unit_of_work = SqlAlchemyCustomerActivitiesUnitOfWork
    logger = StructuredLogger

    <span class="hljs-comment"># entry points</span>
    command_entry = CustomerActivitiesCommandEntry
    query_entry = CustomerActivitiesQueryEntry

    <span class="hljs-comment"># commands</span>
    ScheduleItemCommand = decorate(CommandLoggerHandler, ScheduleItemHandler)
    MarkItemAsDoneCommand = MarkItemAsDoneHandler

    <span class="hljs-comment"># queries</span>
    GetScheduledItemQuery = decorate(QueryLoggerHandler, GetScheduledItemQueryHandler)
    GetAgendaItemsQuery = decorate(QueryLoggerHandler, GetAgendaItemsQueryHandler)
</code></pre>
<p>I the future we might get such a nice way to apply the Decorator Pattern. It's supported currently by using <code>this</code> proxy and inner-class Injector containers which makes it very hard to read.</p>
<h2 id="heading-summary">Summary</h2>
<p>DI in Python is not a popular subject. We have 3 libraries that match the definition:</p>
<ul>
<li><a target="_blank" href="https://github.com/alecthomas/injector">alecthomas/injector</a> I do not like its interface, but I know it's being used in production by some people</li>
<li><a target="_blank" href="http://python-dependency-injector.ets-labs.org/introduction/di_in_python.html">ets-labs/python-dependency-injector</a> very expanded library, with constant support, the problem is it's boilerplate, if that does not bother you, then it's a great choice</li>
<li><a target="_blank" href="http://python-dependency-injector.ets-labs.org/introduction/di_in_python.html">proofit404/dependencies</a> (Injector) simple, but provided all the necessary features. If you need something that's not provided then just think about the design in your application, cause the flow might be somewhere there. Beautiful configuration. Perfect match for agile projects ;)</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Is that Dependency Injection or Service Locator Pattern?]]></title><description><![CDATA[I have to admit to something. For the last 2 years, I was using Service Locator Pattern in one of my projects while being completely convinced that I was…]]></description><link>https://blog.wasinski.dev/dependency-injection-service-locator-1</link><guid isPermaLink="true">https://blog.wasinski.dev/dependency-injection-service-locator-1</guid><category><![CDATA[design patterns]]></category><category><![CDATA[design principles]]></category><category><![CDATA[dependency injection]]></category><dc:creator><![CDATA[Tomasz Wąsiński]]></dc:creator><pubDate>Fri, 04 Dec 2020 12:49:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1637930855076/KPk26eZYb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I have to admit to something. For the last 2 years, I was using Service Locator Pattern in one of my projects while being completely convinced that I was using Dependency Injection, but it turns out that I'm not alone in making such a mistake. What are the differences, what are the consequences of being wrong, and how to distinguish these two patterns?</p>
<p>Let's start with a quick primer, as it turns out definitions do matter, and they can be very helpful, if, and when one understands them correctly.</p>
<h2 id="heading-dependency-injection-101">Dependency Injection 101</h2>
<p>By Wikipedia:
<em>Dependency injection is a technique in which an object receives other objects that it depends on</em>.
The injection can happen in several ways, from which the most important and most often used is <em>constructor injection</em>.</p>
<p>Without DI - building the <code>Service</code> is done by the <code>Client</code> class:</p>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self.my_service = Service()
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">method</span>(<span class="hljs-params">self</span>):</span>
        self.my_service.use()
</code></pre>
<p>With DI - <code>Service</code> class instance is built <em>outside</em> and passed to the <code>Client</code> class:</p>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, my_service</span>):</span>
        self.my_service = my_service
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">method</span>(<span class="hljs-params">self</span>):</span>
        self.my_service.use()
</code></pre>
<p>The essential goal of DI is dividing the <em>build phase</em> of an object from the <em>usage phase</em>, which in return gives us a much more clearer code and greater reusability, as we can use polymorphism thanks to this pattern.</p>
<p>Let me stress that the single most pronounced feature of DI is <strong>passing the dependency from the outside</strong>.</p>
<h2 id="heading-service-locator-pattern-101">Service Locator Pattern 101</h2>
<p>It's yet another technique for providing client classes with proper dependencies. It consists of using the in client class a static <em>registry</em> which then the client class asks for the needed dependency.</p>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, service_locator</span>):</span>
        self.service_locator = service_locator

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">method</span>(<span class="hljs-params">self</span>):</span>
        my_service = self.service_locator.get(<span class="hljs-string">'my_service'</span>)
        my_service.use()
</code></pre>
<p>So in the case of the Service Locator pattern, the most pronounced feature is that the <code>Client</code> class does <strong>not receive</strong> the dependency but in turn <strong>asks</strong> for it the <em>service locator</em> also known as a <em>registry</em>.</p>
<p>Service Locator pattern is commonly considered as an anti-pattern, because the dependencies are not explicit, they cannot be checked by static type checkers; the pattern encourages to build god-classes, and it is very hard to test such code because you need to mock the service locator itself to be able to pass a particular fake-dependency.</p>
<p>The pattern, however, does have some pros: using it allows for quick development of the application, as the developer does not need to carefully craft the dependency graph of the objects - as the dependencies are built usually lazy - when required, as opposed to DI fashion, which needs an <em>assembly</em> (aka. application bootstrap) phase. But really, the pros definitely do not weigh out the cons, so how did it happen that I was using it?</p>
<h2 id="heading-how-to-distinguish-them-then">How to distinguish them then?</h2>
<p>First of all, you need to know the two patterns and the differences between them, to be honest, I haven't heard about Service Locator Pattern until I didn't start wondering why is it so hard to test the code in our project? We were using a library that claimed to be a Dependency Injection container, and because I did not know the second pattern I believed in what it claimed.</p>
<p>I did know the name <em>Service Locator</em>, but because I also knew it was an anti-pattern I did not invest in really understanding what that name means - lessons learned: know the anti-patterns to not make them by yourself and do not believe in everything that is written on the Internet ;)</p>
<p>I've mentioned before that the definitions are often useful, and I think that this is such a case, so for better understanding let me present a metaphor so it sticks with you:</p>
<p><em>imagine manufacture with many positions with different roles and needs - particularly a set of tools. Positions are our client classes and the tools are the dependencies. In the case of the Service Locator Pattern, there is a manager which runs from position to position and delivers the required set of tools "on the go". In the case of Dependency Injection, there is a manager who knows the needs of each position and puts the right tools at the start of the workday.</em></p>
<h2 id="heading-its-not-always-that-plain-and-simple">It's not always that plain and simple...</h2>
<p>...and that's the problem!
The main reason for me not realizing sooner that we aren't using DI but SL was lack of knowledge, but the second was that the library which we were using most likely introduced SL pattern also without the knowledge that it stopped being DI.</p>
<p>So first our classes looked like so:</p>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span>:</span>
_   @inject
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, service: Service</span>):</span>
        self.my_service = service

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">method</span>(<span class="hljs-params">self</span>):</span>
        self.my_service.use()
</code></pre>
<p>notice the <code>@inject</code> decorator which is responsible for injecting the dependencies from the container to the client class (based on the given type annotation).</p>
<p>But the author of the library made a design twist, which made the code prettier but had disastrous consequences:</p>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span>:</span>
    my_service: Service = Inject()

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">method</span>(<span class="hljs-params">self</span>):</span>
        self.my_service.use()
</code></pre>
<p>notice how the <code>__init__</code> method is not even needed anymore because the solution resolved to use the descriptor, which works lazily - implicitly it uses a static registry under the hood, making it an example of a service locator pattern. Knowing what I know now it's quite obvious to me, but at that time it really wasn't.</p>
<p>To support the argument that the accidental introduction of a Service Locator Pattern is an easy thing to miss <a target="_blank" href="https://github.com/proofit404/dependencies/issues/312">here is a link to a Github issue</a>, in which author of a dependency injection container was thinking about a similar solution to the one above, also using a descriptor.</p>
<p>Also, notice how misusing a dependency container makes it a service locator:</p>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, di_container</span>):</span>
        self.di_container = di_container

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">method</span>(<span class="hljs-params">self</span>):</span>
        my_service = self.di_container.get(<span class="hljs-string">'my_service'</span>)
        my_service.use()
</code></pre>
<p>So whenever one passes the whole container to a client class it actually introduces a completely different pattern.</p>
<h2 id="heading-summary">Summary</h2>
<p>Things to remember:</p>
<ul>
<li>Dependency Injection is all about passing the dependencies from the outside into the client class, preferable while constructing the client class</li>
<li>Service Locator Pattern, in turn, resolves to the client class itself getting the dependencies with the help of a special <em>service locator</em>, usually a global or static registry.</li>
<li>It's possible to introduce the Service Locator pattern while being in good faith of using Dependency Injection, often by injecting the whole container, or by attaching the SL pattern to the client class with a construct like e.g. a descriptor.</li>
<li>It's good to know and understand some anti-patterns, to know what <strong>not</strong> to do.</li>
<li>Service Locator isn't always bad and can be useful for wiring up the whole application but that's a longer topic.</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Timezone handling pitfalls - part 2]]></title><description><![CDATA[This time I will focus on issues that arise when multiple users have to coordinate to a particular time, but they still can be in different timezones. Note…]]></description><link>https://blog.wasinski.dev/timezone-handling-pitfalls-2</link><guid isPermaLink="true">https://blog.wasinski.dev/timezone-handling-pitfalls-2</guid><category><![CDATA[time]]></category><category><![CDATA[Design]]></category><dc:creator><![CDATA[Tomasz Wąsiński]]></dc:creator><pubDate>Fri, 20 Nov 2020 12:28:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1637929647586/4e1UN2yB0.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This time I will focus on issues that arise when multiple users have to coordinate to a particular time, but they still can be in different timezones.</p>
<p>Note that this is a continuation from <a target="_blank" href="/timezone-handling-pitfalls-1">the previous post which you can find here</a>.</p>
<p>Let's recall our example domain:</p>
<ul>
<li>we are dealing with <em>task scheduling</em></li>
<li><em>the user can schedule a task for an arbitrary day in the future, and when that day comes she can mark it as done</em></li>
<li><em>our users travel a lot, so they do not stick to just one timezone, we would like to allow them to complete the tasks wherever they currently are</em></li>
</ul>
<p>which led us to implement <em>floating timezones</em> as I like to call it - business logic dependent on the user's local timezone, and storing the dates in the naive form (not timezone-aware). All the details are in the previous part.</p>
<p>But the latest requirement destroyed our previous concept:</p>
<ul>
<li><em>We would like to introduce Teams, where users could rival on how many Tasks they complete. To make it fair, this time we will stick to one timezone for Tasks which will count towards the score</em></li>
</ul>
<p>This time we cannot use the user's local time, as it would not be fair to other users. We need to stick to a particular timezone against which we will validate the business rules, but additionally, we would still like to show to the users the time left to complete a particular Team Task considering their current timezone, as our users still travel a lot.</p>
<h2 id="heading-timezone-handling-isnt-simple-and-is-not-easy">Timezone handling isn't simple and is not easy</h2>
<p>The time zones stuff tends to boil the brains of people, even experienced developers, and it wasn't different from me.
I'll try to give you some examples of the problems that arise here.</p>
<p><em>As a User I would like to see the deadline to finish a task</em></p>
<ul>
<li><p><em>when I'm in the Team common timezone</em></p>
<p>  e.g CET (UTC-1), and assuming tasks usually last until an end of a day, but for the local time of the whole Team. So this means that we can have a Task which can be done between <code>24.09.2020 - 00:00</code> to <code>24.09.2020 - 23:59</code> CET, but when you convert it to UTC to store it into the database it is then <code>23.09.2020 - 23:00</code> to <code>24.09.2020 - 23:59</code>, then when the client (for example a mobile app) in CET timezone is requesting for details of such Task the time has to be shifted to CET, usually that shift is done by the client, as the client knows in which timezone it is.</p>
</li>
<li><p><em>when I'm traveling to a different timezone</em> e.g. New York time</p>
<p>  This part is quite similar: a Task is stored in UTC, New York is UTC-5 so the datetimes visible in the client are <code>23.09.2020 - 17:00</code> to <code>24.09.2020 - 16:59</code>, however, please notice one thing: if previously all the Tasks had a deadline at the end of the day (local time), then it now turns out that depending on the location of the client the deadline and availability of the Task to finish might happen somewhere in the mid-day!</p>
</li>
</ul>
<p>For both of these examples also notice that it is the mobile client which "knows" in which timezone it is, thus we could do the conversion on the mobile client, the backend would return UTC datetimes, and the client would shift them appropriately, this is a common approach, right? But it will not work in our case, or would work poorly, let's examine why.</p>
<p>We have a Task scheduled for  <code>24.09.2020 - 00:00</code> to <code>24.09.2020 - 23:59</code> UTC, the mobile client is in New York (-5h) which makes the task available from <code>23.09.2020 - 19:00</code> to <code>24.09.2020 - 18:59</code> local time. When the mobile client what's to view tasks for 23.09 it has to send that date in the request obviously, but look what happens now: the server does not know in which timezone is the mobile client, so it does not know how to convert 23.09 into UTC datetime period which matches that date, so the only possibility would be to convert that period using maximal and minimal possible timezone shifts (-11 / +14 hours) which makes the period greater than 24h, resulting in returning Tasks to the client that are possibly one day before or after the requested date, leaving to the mobile client the task of shifting and cleaning the data.</p>
<p>There is a better approach: just send to the server not only the local time but also the timezone, leaving the conversion for the server, so that it perfectly knows for what period return the Tasks. To make this conversion behavior consistent we should also do the conversion back from UTC to local time on the server.</p>
<h2 id="heading-when-timezones-change-their-time">When timezones change their time...</h2>
<p>Another problem that arises here is the changes in the <em>common</em> timezone of the Team. That's exactly the thing that previously mentioned <em>floating timezones</em> handle so well by just using local time without any timezone information, but due to previously mentioned "fairness" reasons, we cannot use them here. A perfect example of a very common time shift is the introduction of <em>daylight saving time</em>, still so common in Europe. What it does is change the relation of the Team's <em>common timezone</em> from for example -1 to -2 in Summer.</p>
<p>There's no simple solution to this problem, the easiest is to take into account the appropriate shift when first converting the time to UTC, so for example when 2 Tasks are being scheduled, the first one for the date when there will be still CET time apply -1h, and the second already in the CEST - apply -2h shift. That's the easy part, because if you know the date you know if it will be with or without DST shift.</p>
<p>If you ever encounter however a whole timezone shift, as it happened in Samoa Island around 2011 then I guess that it will require changing affected dates already written to the database.</p>
<h2 id="heading-job-scheduling">Job scheduling</h2>
<p>Another problem, however, lies in scheduled jobs, which often are triggered based on a schedule. For example, when a Competition starts all of the competitors get a notification, it happens every Monday at 7:00, local time of course. Three solutions to that:</p>
<ul>
<li>Hardcode the schedule and reconfigure the application when required. Easiest but let's face it, not the most pleasant approach, and will not work if you need to support multiple different timezones.</li>
<li>Fire a scheduled job at least once per hour but base the job on a datetime taken from the database, which will be a UTC datetime</li>
<li>Schedule jobs dynamically using a library like <a target="_blank" href="https://apscheduler.readthedocs.io/en/stable/">APScheduler</a> </li>
</ul>
<h2 id="heading-converting-to-local-time-sometimes-does-not-make-sense">Converting to local time sometimes does not make sense</h2>
<p>While developing the project it occurred to us that sometimes it does not make sense to convert times to the local timezone, or at least it feels clumsy to do so. One of the views in the mobile app was showing an aggregated number of completed Tasks in a particular day: if the user finished 3 Tasks of 4 at 25.09.2020 the view showed these numbers, it worked fine for so-called <em>floating timezones</em> when the datetimes were saved in the naive form, but when we introduced timezone-awareness it got weird because depending on the local timezone that finished Task might have counted for different dates or often two dates at once (recall a Task being available to do between mid-day hours despite being scheduled for the start of the day but in a different timezone). How to treat some cases? To be honest I do not know, as I think depends purely on the UX, in our case we just ditched that feature.</p>
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="/timezone-handling-pitfalls-1">Same as in my previous article</a></p>
]]></content:encoded></item><item><title><![CDATA[Timezone handling pitfalls]]></title><description><![CDATA[Recently I have had the pleasure to work as a technology leader on a project that requires proper implementation of timezone handling, over some time I…]]></description><link>https://blog.wasinski.dev/timezone-handling-pitfalls-1</link><guid isPermaLink="true">https://blog.wasinski.dev/timezone-handling-pitfalls-1</guid><category><![CDATA[time]]></category><category><![CDATA[Design]]></category><dc:creator><![CDATA[Tomasz Wąsiński]]></dc:creator><pubDate>Sat, 05 Sep 2020 11:19:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1637928886910/QT2sHAx8n.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Recently I have had the pleasure to work as a technology leader on a project that requires proper implementation of timezone handling, over some time I learned, sometimes the hard way quite a lot on this topic.</p>
<h2 id="heading-short-intro-of-the-domain">Short intro of the domain</h2>
<p>Let us introduce an example domain: task scheduling, <em>the user can schedule a task for an arbitrary day in the future, and when that day comes she can mark it as done</em>. Later on, we will add more requirements. For now:</p>
<p><code>can_mark_as_done IF Task.scheduled_for &lt;= UTC_NOW.date()</code></p>
<p>A rule of thumb is to use UTC as a default for your application and servers, so that's what we do here.</p>
<p>Now, let's suppose that the user lives in CET timezone which is UTC+1, this will break our logic: the user won't be able to mark the <code>Task</code> as done between 00:00-01:00 local time because at that time it's still <em>the previous day</em> in the UTC timezone.</p>
<p>How to solve it? There are a couple of possibilities, let's examine the first one</p>
<h2 id="heading-changing-the-server-time-eg-use-datetimenow-instead-of-datetimeutcnowin-python-terms">Changing the <em>server time</em>, e.g. use <code>datetime.now()</code> instead of <code>datetime.utcnow()</code>(in Python terms)</h2>
<p>Easy, and simple, works like a charm until we won't have users from other parts of the world, other than our server's timezone. <em>Won't fix</em> as they say.</p>
<h2 id="heading-using-timezone-aware-type-for-the-taskscheduledfor-attribute">Using timezone-aware type for the <code>Task.scheduled_for</code> attribute</h2>
<p>Fixes our logic, but has one substantial drawback - databases do not work well with tz-aware types, for example, Postgres stores the timestamp normalized to UTC and does not store the information about the timezone, we would need to use a separate field to store it. So why complicate stuff? <em>Won't fix</em></p>
<h2 id="heading-converting-taskscheduledfor-value-to-utc-shifted-from-the-users-local-timezone-upon-object-creation">Converting <code>Task.scheduled_for</code> value to UTC shifted from the user's local timezone upon object creation.</h2>
<p>So instead of saving just the day, for example, <code>2020-12-12</code> we would transform it to datetime object <code>2020-12-12T00:00</code> and apply the shift resulting in <code>2020-12-11T23:00</code>. That way our logic would work smoothly around midnight. And if we would need to query for this field the database would use a naive datetime type.</p>
<p>But... isn't this a bit too complex? Let us introduce one more requirement: <em>our users travel a lot, so they do not stick to just one timezone, we would like to allow them to complete the tasks wherever they currently are</em></p>
<p>Because we saved the time upon creation, we are limited to that timezone, each time the user would travel to a different timezone we would need to adjust the value - that's pointless. So <em>won't fix</em>.</p>
<h2 id="heading-using-simply-local-time-to-validate-the-rules">Using simply local time to validate the rules.</h2>
<p>Instead of using our <em>server time</em> to validate the logic, why not use user's local time? Something like this: <code>can_mark_as_done IF Task.scheduled_for &lt;= LOCAL_DATETIME_NOW.date()</code>. In a web application, we can have the <em>local datetime</em> delivered via a header on each request. Obviously, this loosens up the business rule quite substantially, but it actually happened earlier when we allowed our users to travel ;) One way to prevent "cheating" is to validate the incoming datetime if it is plausible - somewhere between -11 and +14 from current UTC time - as these are the largest possible time shifts.</p>
<p>The above solution is very easy to implement, works fantastic with mobile apps - always adjusting to the user's timezone. My team and the client were very happy with this solution. Until one day.</p>
<h2 id="heading-new-requirement-coming">New requirement coming</h2>
<p><em>We would like to introduce Teams, where users could rival on how many Tasks they complete. To make it fair, this time we will stick to one timezone for Tasks which will count towards the score</em>.</p>
<p>Oh my, and our perfect solution just went down the drain. <a target="_blank" href="/timezone-handling-pitfalls-2">I will get back to this subject in my next post</a>.</p>
<h2 id="heading-things-to-remember">Things to remember</h2>
<ul>
<li>use plain naive types, which work well with databases</li>
<li>storing UTC works great with dates in the past but for future dates, it becomes unnecessarily complex</li>
<li>when possible, store naive-local date/datetime and evaluate it "when the time comes" against a local datetime, I call this approach <em>floating timezones</em></li>
</ul>
<h2 id="heading-further-reading-sources">Further reading / sources</h2>
<ul>
<li><a target="_blank" href="http://www.creativedeletion.com/2015/03/19/persisting_future_datetimes.html">How to save datetimes for future events - (when UTC is not the right answer)</a></li>
<li><a target="_blank" href="https://www.postgresql.org/docs/11/datatype-datetime.html">Postgres documentation 8.5.1.3 timestamp tz-aware</a></li>
<li><a target="_blank" href="https://stackoverflow.com/a/2532962/5792269">StackOverflow - Good starting point for learning about timezone handling pitfalls</a></li>
<li><a target="_blank" href="/timezone-handling-pitfalls-2">Part II of this series</a>.</li>
</ul>
]]></content:encoded></item></channel></rss>