I'm trying to do some simple dependency injection in Python. For example:
logic.py
class A(object):
def __init__(self):
print("A")
class B(object):
def __init__(self, a = A()):
self.a = a
So A() is being called as a default argument to B()
main.py
from logic import B #this calls A()
if __name__ == "__main__":
print("main") # No concrete call to B() or A()
output:
A
main
Could anyone explain why A() is called, if all I did was to import B? Why would calling import B run the __init__ of A?
By the way, to solve it all it takes is to change the __init__ to:
class B(object):
def __init__(self, a = None):
if not a:
a = A()
self.a = a