Reload Modified User-Defined Python Module

This example shows how to reload a modified Python® module.

When you use this workflow, MATLAB® deletes all variables, scripts, and classes in the workspace. For more information, see the clear classes function.

The Python calling syntax to reload the module depends on your Python version. To verify your Python version, use the MATLAB pyenv function.

Create Python Module

Change your current folder to a writable folder. Open a new file in MATLAB Editor.

Copy these statements defining a myfunc function and save the file as mymod.py.

def myfunc():
    """Display message."""
    return 'version 1'

Call myfunc.

py.mymod.myfunc
ans = 

  Python str with no properties.

    version 1

Modify Module

Modify the function, replacing the return statement with the following:

    return 'version 2'

Save the file.

Unload Module

clear classes

MATLAB deletes all variables, scripts, and classes in the workspace.

Import Modified Module

mod = py.importlib.import_module('mymod');

Reload Module in Python Version 2.7

py.reload(mod);

Reload Module in Python Versions 3.x

py.importlib.reload(mod);

Call Function in Updated Module

Call the updated myfunc function.

py.mymod.myfunc
ans = 

  Python str with no properties.

    version 2

See Also

|

Related Topics