1

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
Community
  • 1
  • 1
Omri374
  • 2,555
  • 3
  • 26
  • 40
  • Not exactly the same case. It's not about A being mutable or not, it's about A being called in the first place, or am I missing anything? – Omri374 Jun 25 '19 at 16:09
  • 2
    The answers to that question answer your question. `A()` is being evaluated and called *while `B.__init__` is being defined*, i.e. at "parse time". See the duplicate for many answers as to *why*. – deceze Jun 25 '19 at 16:10

0 Answers0