# Using Dependency Injection in Python to Make Date-Dependent Code Deterministic and Testable

DevFeed: [Using Dependency Injection in Python to Make Date-Dependent Code Deterministic and Testable](<https://devfeed.tech/articles/stop-using-datetime-now-33928.md>)

Original publisher: [Read original article](<https://hakibenita.com/python-dependency-injection>)

Author: Haki Benita

Published: 2020-05-31T21:00:00Z

Content type: article

Language: en

Sources: [Haki Benita](<https://devfeed.tech/sources/haki-benita.md>)

Topics: [Dependency injection](<https://devfeed.tech/topics/dependency-injection.md>), [Python](<https://devfeed.tech/topics/python.md>), [DateTime](<https://devfeed.tech/topics/datetime.md>), [Testing](<https://devfeed.tech/topics/testing.md>)

Tags: [articles](<https://devfeed.tech/tags/articles.md>), [dependency-injection](<https://devfeed.tech/tags/dependency-injection.md>), [django](<https://devfeed.tech/tags/django.md>), [nondeterminism](<https://devfeed.tech/tags/nondeterminism.md>), [python](<https://devfeed.tech/tags/python.md>), [test](<https://devfeed.tech/tags/test.md>), [testing](<https://devfeed.tech/tags/testing.md>)

## AI overview

This article explains how dependency injection can make Python code that depends on the current date deterministic and easier to test. It uses a function returning tomorrow's date to show why hard-coded time references create fragile tests, and presents passing the reference date as an argument as an alternative to mocking or external libraries.

## Source excerpt

If you ever had a test that one day just started to fail, unprovoked, or a test that fails once every blue moon for no apparent reason, it's possible your code is relying on something that is not deterministic. In this article I describe a practical approach to dependency injection in Python that when used correctly, can eliminate nondeterminism and make your code easier to maintain and to test.