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

11 次查看(过去 30 天)
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?

回答(1 个)

Max
Max 2025-5-13
编辑:Max 2025-5-13
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:

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

产品


版本

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by