While much of the Python community seem to believe the use of duck typing and monkey patching render dependency injection irrelevant in Python (see Stackoverflow link below) I find myself perpetually running into the issue described in Cosmic Python:
The standard way to do things is to declare our dependency implicitly by simply importing it, and then if we ever need to change it for tests, we can monkeypatch, as is Right and True in dynamic languages...but in real life, you’d end up having to call
mock.patch
for every single test that might cause an out-of-stock notification. If you’ve worked on codebases with lots of mocks used to prevent unwanted side effects, you’ll know how annoying that mocky boilerplate gets.
It goes on:
And you’ll know that mocks tightly couple us to the implementation. By choosing to monkeypatch
email.send_mail
, we are tied to doingimport email
, and if we ever want to dofrom email import send_mail
, a trivial refactor, we’d have to change all our mocks.
What I find frustrating is that many of the responses to the popular Stackoverflow question Why is IoC / DI not common in Python? seem to imply a lack of understanding either of DI itself or of its utility - see comments 1, 2, 3, 4.
Raymond Hettinger proposes an intriguing alternative to DI but it isn't apparent to me how this would look in a test context...
What am I missing here???