Matlab does not recognise changes in user-defined python modules. Can I work around this without restarting Matlab or using clear classes?

10 visualizaciones (últimos 30 días)
I am calling a python function myfun from the module mymodule using the syntax:
y = py.mymodule.myfun(x)
This works fine usually. But if I make some changes to myfun then execute the code again, Matlab continues to call the old version of myfun.
Other posts dealing with similar issues (including the official Matlab documentation) suggest solutions involving restarting Matlab or a call to clear classes, with possibly the most generally useful one being this.
However, I am wondering if there is a solution that erases the need to explicitly call some sort of reload function whenever it might be necessary? So that "production" code might be identical to the last iteration of "development" code?

Respuestas (1)

Max
Max el 13 de Mayo de 2025
Editada: Max el 13 de Mayo de 2025
The simple solution is this. Rather than using
y = py.mymodule.myfun(x);
Instead, use
mymod = py.importlib.import_module('mymodule');
py.importlib.reload(mymod);
y = mymod.myfun(x);
This (apparently) ensures you will be calling the latest (saved) version of mymodule whenever you call myfun - at least while running Matlab version 2024b with Python version 3.12.
I am answering my own question because I have read through plenty of threads (see below for some of them) and not seen this relatively simple solution anywhere. I hope it can help others and save them some time.
Some related threads:
  1 comentario
Max
Max el 13 de Mayo de 2025
I have realised too late that the proposed solution above only works for some kinds of edits, as already mentioned in this thread. I'm still not sure why

Iniciar sesión para comentar.

Categorías

Más información sobre Call Python from MATLAB en Help Center y File Exchange.

Productos


Versión

R2024b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by