0

I'm working on a project that wraps scipy.odr with (hopefully) a simple GUI using PyQt5. As the documentation demands the Model class accepts functions which are defined precisely as such:

def linear_fit(a, x):
    return a[0] * x + a[1] 

(A parametrs vector as the first argument and the free variable x as the second)

My intention is that the user will write a separate python script containing exactly one function, like the one defined above, without the need to define it inside the GUI python script (which I write and don't want the user to touch).

It is easy enough to make the user load the script with PyQt5 QFileDialog and get the absolute path to the script with a function like this one:

def browsefiles(self):
    fname = QFileDialog.getOpenFileName(self, 'Open File', 'C:', 'Python Script (*.py)')
    self.lineEdit_path.setText(fname[0])
    self.script_path = fname[0]

Next I want another button which when pressed will execute the fitting procedure as described in the documentation. What I can't figure out is how to pass the function that the user wrote to the Model class inside the script where I wrote the GUI.

I can't import the user's script at the begining of the file because I don't know where the user saved his script before she loaded it using the GUI, and I can't even specify the function name because the user may call her function however she likes.

I would love some help solving this problem.

My GUI looks something like this:

from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
import scipy.odr as odr


class FitGUI(QMainWindow):

    def __init__(self):
        super(FitGUI, self).__init__()
        loadUi('fitgui.ui', self)

        self.pushButton_browse.clicked.connect(self.browsefiles)  # The function that I wrote above

        self.pushButton_fit.clicked.connect(self.fit)

        self.show()

    def fit(self):
        model = odr.Model(...)  # Here I want to pass the function that the user defined in a separate script
        ...  # The rest of the fitting procedure as described in the documentation

def main():
    app = QApplication([])
    window = FitGUI()
    app.exec()


if __name__ == '__main__':
    main()
Alon
  • 3
  • 2
  • you can use module `importlib` to load other module ising string with name. But for function's name it would be simpler if every user would use the same name. And this is how all plugins work - they always have to use the same names. – furas Apr 24 '22 at 00:52

1 Answers1

0

After the comment from furas I researched a bit and quickly found out this answer by Stefan Scherfke in a similar post, and used his function inside my GUI script.

Thank you.

Alon
  • 3
  • 2