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

9 views (last 30 days)
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?

Answers (1)

Max
Max on 13 May 2025
Edited: Max on 13 May 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 Comment
Max
Max on 13 May 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

Sign in to comment.

Products


Release

R2024b

Community Treasure Hunt

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

Start Hunting!