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

조회 수: 9 (최근 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:
  댓글 수: 1
Max
Max 2025년 5월 13일
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

댓글을 달려면 로그인하십시오.

카테고리

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