I know that in Java dependency injection makes life better. There are a lot of annotation processor frameworks that map beans to objects and conveniently inject them into a right place.
But I never heard about dependency injection
in Python or Ruby, for example. Do this languages have build-in support for it? Or they don't need it? Why?

- 10,681
- 20
- 92
- 192
-
2A fun topic, but too broad. – Robert Moskal Oct 21 '15 at 18:55
1 Answers
In short, In Python, dependency injection is less important than it is in Java because of the stateful nature of modules and the role of metaprogramming.
In languages like Java, classes typically define blueprints for objects, which must be instantiated at runtime by whatever imports them. When you import a class, you only get the recipe for the class.
Conversely, in Python importing a module can do a lot more. During an import, you are essentially running a module's code within a namespace - meaning that the module can not only construct singletons referenced by the module itself, but can even perform complex tasks like connecting to databases during execution of the import. When two modules import the same referenced module, the second module inherits Python's evaluated concept of the module from when it was first imported, preserving and changes the first importer may have made. Furthermore, its much less painful to scan for submodules in Python and Ruby than it is in Java, which more frameworks use module placement to indicate function (such as models.py in Django) than you see in Java (which generally favors annotations).
TLDR: modules and classes in Python (and Ruby) are stateful in ways that are painful or impossible to replicate in Java, and the mechanics of the import statement provide most of the interesting parts of dependency injection (although not IoC). It doesn't not-exist, its just not as necessary.
See also: Why is IoC / DI not common in Python?

- 1
- 1

- 109
- 4
-
Do I understand correctly, Python is able to import objects (modules) with some nondefault states? Do modules have some preprocessing to achieve nondefault state after importing? – Rudziankoŭ Oct 21 '15 at 21:27
-
1@Rudik The 'preprocessing' in question - which really amounts simply to interpreting - occurs during runtime. When you import a python module, Python runs the code that composes it and stores the result under the module's name. Python keeps a hidden (meaning accessible via double underscore) registry of all imported modules in memory. Importing a module which python already knows about results in a reference to that module as opposed to a new invocation of its definition code, allowing multiple importers in a program to reference a module - which is effectively a singleton. – Uncommented Oct 21 '15 at 21:34