From 32d5de335852bf4c542a6d3b1dc608bbcea880d6 Mon Sep 17 00:00:00 2001 From: Axel Matstoms Date: Thu, 6 Mar 2025 14:38:58 +0100 Subject: [PATCH] Add session kwarg to ModelicaSystem constructor If the session kwarg is specified, the ModelicaSystem will use that session instead of creating a new one. This is useful for creating a ModelicaSystem for a model that is already loaded in an already existing session. Remove __del__ method from ModelicaSystem. Having the deleter there meant that the deleter for the session would run multiple times if a session had shared ownership. The deleter will still run when the session's reference count reaches zero, or when it is garbage collected. --- OMPython/__init__.py | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/OMPython/__init__.py b/OMPython/__init__.py index bd5fc198b..ea7f154ec 100644 --- a/OMPython/__init__.py +++ b/OMPython/__init__.py @@ -821,7 +821,7 @@ class ModelicaSystem(object): def __init__(self, fileName=None, modelName=None, lmodel=None, useCorba=False, commandLineOptions=None, variableFilter=None, customBuildDirectory=None, verbose=True, raiseerrors=False, - omhome: str = None): # 1 + omhome: str = None, session: OMCSessionBase = None): # 1 """ "constructor" It initializes to load file and build a model, generating object, exe, xml, mat, and json files. etc. It can be called : @@ -831,11 +831,14 @@ def __init__(self, fileName=None, modelName=None, lmodel=None, Note: If the model file is not in the current working directory, then the path where file is located must be included together with file name. Besides, if the Modelica model contains several different models within the same package, then in order to build the specific model, in second argument, user must put the package name with dot(.) followed by specific model name. ex: myModel = ModelicaSystem("ModelicaModel.mo", "modelName") """ + if session is not None: + self.getconn = session + elif useCorba: + self.getconn = OMCSession(omhome=omhome) + else: + self.getconn = OMCSessionZMQ(omhome=omhome) + if fileName is None and modelName is None and not lmodel: # all None - if useCorba: - self.getconn = OMCSession(omhome=omhome) - else: - self.getconn = OMCSessionZMQ(omhome=omhome) return self.tree = None @@ -857,11 +860,6 @@ def __init__(self, fileName=None, modelName=None, lmodel=None, self._verbose = verbose - if useCorba: - self.getconn = OMCSession(omhome=omhome) - else: - self.getconn = OMCSessionZMQ(omhome=omhome) - ## needed for properly deleting the OMCSessionZMQ self._omc_log_file = self.getconn._omc_log_file self._omc_process = self.getconn._omc_process @@ -906,9 +904,6 @@ def __init__(self, fileName=None, modelName=None, lmodel=None, self.buildModel(variableFilter) - def __del__(self): - OMCSessionBase.__del__(self) - def setCommandLineOptions(self, commandLineOptions: str): ## set commandLineOptions if provided by users if commandLineOptions is not None: