Understanding Python and MATLAB import Commands

The import statement does not have the same functionality in MATLAB® as in Python®. Python uses the import statement to load and make code accessible. MATLAB uses the import function to refer to a class or function without using the package name.

Caution

Never call:

import py.*

If you do, then MATLAB calls the Python function instead of the MATLAB function of the same name. This can cause unexpected behavior.

If you call this command, then you must call the MATLAB command:

clear import

Do Not Type import pythonmodule

MATLAB automatically loads Python when you type:

py.command

Do not type in MATLAB:

import pythonmodule

Use MATLAB import to Shorten Class or Function Names

The Python from...import statement lets you reference a module without using the fully qualified name. Suppose that you have the following Python code, where y is a class or function name that you want to use.

from x import y

Replace this statement with the following MATLAB code:

import x.y

For example, the Python textwrap module formats blocks of text.

S = py.textwrap.wrap('This is a string');

Since wrap is not a MATLAB function, you can shorten the calling syntax using the import function. After calling this command, you do not need to type the package (py) and module (textwrap) names.

import py.textwrap.wrap
S = wrap('This is a string');

See Also