4 ms·
> Oddly enough, dependency injection isn't that popular in Python Because you don't need dependency injection in python. You can mock out any object anywhere d
by nhumrich 5y ago
> Oddly enough, dependency injection isn't that popular in Python
Because you don't need dependency injection in python. You can mock out any object anywhere during your tests.
- jseban 5y ago> Because you don't need dependency injection in python. You can mock out any object anywhere during your tests. Exactly! I recommend anyone who comes in contact with dependency injection to really think about this.
- necovek 5y agoWhen discussing these in Python, you need to be careful to differentiate between "mocking" and "monkey patching", especially so because both of those are provided by Python's standard library "mock" module. Mocking, and specifically mocking with Python mock module, is a quick approach to construct faked objects that simply do not fail and which log any method execution on them. Dependency injection is usually done with more complete fakes, ideally with tested fakes (fakes which pass the same sets of tests as the original, "production" implementation does). Monkey-patching is what allows Python developers to avoid dependency injection altogether. It has its own set of risks (basically, it might affect things you are unaware of), though you can reduce those by patching exactly at the import place of your dependency (eg. patch("mymodule.utc_now") vs patch("datetime.datetime.utc_now") — if you are not doing that today, start now! :). Still, I consider readability the main concern when programming, with testability being second (no surprise they are closely related, as tests will document behaviour precisely). With Python's monkey-patching and mocking, you are at a large risk of producing illegible gibberish, both in tests and code. If you can at all avoid it, you should! Simple dependency injection by passing dependencies directly in (functions or classes) makes everything explicit and trivial to comprehend (and test). Unfortunately, the biggest problem is that the world of Python libraries is completely filled with magic side effects, so you sometimes can't effectively avoid doing either of those (it would be too costly).
- ptx 5y agoWhat about when there's some environment-specific (or otherwise problematic) dependency that you need to mock because it can't be imported where you want to run the unit tests? Patching it afterwards doesn't work when the import of the default implementation fails. If you patch it ahead of time by inserting a dummy module, that dummy module might be used to initialize other modules that you weren't targeting, so undoing the patch after the test might be very tricky. You can sort of make it work, but it seems really hacky, so for that reason I'm currently refactoring towards DI (without frameworks). But I'm open to better ideas.