Search code examples
pythonquart

Python : Passing parameters by reference down chain


I am trying to pass a variable (MySQL connection class instance) down into a method and then into a class, the issue is that it needs to be done 'by reference' as the main class can change the value. The variable in the final class does not update though:

application:

def __init__(self, quart_instance) -> None:
    self._db_object : mysql_connection.MySQLConnection = None

def initialise_app(self):
    self.view_blueprint = health_view.create_blueprint(self._db_object)

Health View:

def create_blueprint(db_connector : mysql_connection.MySQLConnection):
    view = View(db_connector)

class View:

    def __init__(self, db_connector):
        self._db_connector = db_connector

When the application performs the database connection in the background in the application I was expecting self._db_connector in the view to update. Any help would be appreciated as I am very confused.


Solution

  • Don't confuse changing the state of an object with changing the value of a variable; the former is visible through all references to that object, the latter only affects that particular variable.

    For this to work, the application's _db_object and the view's db_connector must refer to the same object at all times.

    There are essentially two solutions:

    1. Give MySQLConnection a default state, so you can create one immediately to pass along to View rather than starting with None and modify it later, or

    2. Wrap MySQLConnection in another object that you can do the same with

    Both options have both benefits and drawbacks.