MATLAB Answers

How can I clear specific Python classes/modules from memory without using "clear classes"

108 views (last 30 days)
Emil Geiger
Emil Geiger on 6 Jul 2018
Answered: Emil Geiger on 19 Jul 2018
I have successfully developed a workflow that will allow me to call custom python code from Matlab, see the following two scripts:
MATLAB:
function out = reloadPy() % A Matlab function
clear classes
mod = py.importlib.import_module('mymod');
py.importlib.reload(mod);
v1 = 1:5;
v2 = 6:10;
out = double(py.mymod.add2Vectors(v1,v2));
Python:
# mymod.py - a python function
import numpy
import array
def add2Vectors(v1, v2):
myarray = numpy.array(v1) + numpy.array(v2)
return array.array('d', myarray)
If I call reloadPy from the command line I get the following output:
>> test = reloadPy
Warning: Objects of 'onCleanup' class exist. Cannot clear this class or any of its superclasses.
> In reloadPy (line 2)
Warning: Objects of 'table' class exist. Cannot clear this class or any of its superclasses.
> In reloadPy (line 2)
Warning: Objects of 'datetime' class exist. Cannot clear this class or any of its superclasses.
> In reloadPy (line 2)
test =
7 9 11 13 15
>>
The warnings are stemming from the "clear classes" command. I am using that sequence of commands (lines 2-4) to reload the python module while debugging. Any changes I make to mymod.py are not captured unless I execute all 3 commands. The documentation for "clear" states:
Calling clear all, clear classes, and clear functions decreases code performance, and is usually unnecessary. ...
To clear a particular class, use clear myClass.
Is there a way to just clear just my python class or module? I can't find the name. I tried
[M, X, C] = inmem
But none of the result seem to be related to python.
  1 Comment
Emil Geiger
Emil Geiger on 9 Jul 2018
Update: I can't use this workflow if I pass a variable into reloadPy because clear classes will delete the variable. I have also submitted a support ticket.

Sign in to comment.

Answers (1)

Emil Geiger
Emil Geiger on 19 Jul 2018
I received an answer from Support. Clearing just the python module is not possible at this time. But wrapping the reload statements in a function is a valid work around because any user variables are out of scope. For example:
function reloadPy()
warning('off','MATLAB:ClassInstanceExists')
clear classes
mod = py.importlib.import_module('mat');
py.importlib.reload(mod);

Products


Release

R2017a

Community Treasure Hunt

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

Start Hunting!