Does this design represent circular dependency?

Question:

Imagine this example (that may be run without any errors):

from random import uniform

class Car:    
    def __init__(self, position):
        self.position = position
        self.sensor = Sensor(id, self)

class Sensor:
    def __init__(self, id, carrier_car):
        self.id = id
        self.position = self.compute_position(carrier_car)

    def compute_position(self, carrier_car):
        return [carrier_car.position[0] + uniform(1,3), carrier_car.position[0] + uniform(2,4)]
        
car1 = Car([10,10])
print("This car's sensor coordinate is ({},{}).".format(car1.sensor.position[0], car1.sensor.position[1]))

Question 1.

Given the line self.sensor = Sensor(id, self), I don’t understand how this line runs without any problem. Isn’t this circular dependency? (self, in the argument, is an object of Car which has not yet been completely created (initialized) at the point it is passed to the initializer of Sensor.)

Question 2.

If this a circular dependency, how can I resolve it?

Asked By: User

||

Answers:

The self object that is passed to Sensor(id, self) is an already existing Car instance, but it does not have a sensor attribute yet.

Since Sensor only requires the position attribute of the carrier_car object, this is not a problem, since it has already been created in the line self.position = position.

In any case, this design is a bit confusing. I would not pass a Car object to Sensor, but just a position, as this is all that Sensor needs to know about the car. This would also simplify the code:

from random import uniform

class Car:    
    def __init__(self, position):
        self.position = position
        self.sensor = Sensor(id, position)

class Sensor:
    def __init__(self, id, position):
        self.id = id
        self.position = self.compute_position(position)

    def compute_position(self, position):
        return [position[0] + uniform(1,3), position[0] + uniform(2,4)]
        
car1 = Car([10,10])
print("This car's sensor coordinate is ({},{}).".format(car1.sensor.position[0], car1.sensor.position[1]))
Answered By: mkrieger1
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.