No module or function named error in Python custom function with MATLAB

Hello
I wish to run Python function from MATLAB command window. I have a set of function in the folder.
To make a seemless integration between the two, I did the following:
pyenv
ans =
PythonEnvironment with properties:
Version: "3.12"
Executable: "C:\Users\poulo\AppData\Local\Programs\Python\Python312\python.exe"
Library: "C:\Users\poulo\AppData\Local\Programs\Python\Python312\python312.dll"
Home: "C:\Users\poulo\AppData\Local\Programs\Python\Python312"
Status: Loaded
ExecutionMode: InProcess
ProcessID: "50204"
ProcessName: "MATLAB"
The output appeared as below:
Next, I added the Python Path using the below command
moduleDirPath = 'C:\pganguli\Pyscripts\atmos-main\atmos-main\atmos\'
insert(py.sys.path, int64(0), moduleDirPath)
It added my package 'atmos' to CPython directory. Now, while checking the dir, it showed all the functions
. __pycache__ moisture.py thermo.py
.. constant.py parcel.py utils.py
__init__.py kinematic.py pseudoadiabat.py
Now, I tried to call my function and I receive No module/function error. The python within MATLAB is working fine, Checked with simple calculation, which is working fine
py.numpy.sqrt([2.0 3.0 4.0])
ans =
Python ndarray:
1.4142 1.7321 2.0000
Kindly let me know where I am missing
P = py.numpy.array(101300); T = py.numpy.array(21.3)
q = py.moisture.specific_humidity_from_dewpoint_temperature(P,T) % specific_humidity_from_dewpoint_temperature is the function available in moisture.py module, which require two variable P & T
No module or function named 'moisture'.

 Accepted Answer

Hi @Poulomi,

I reviewed your Python-MATLAB integration issue and can help you resolve the "No module or function named 'moisture'" error. Let me explain the root cause of error, you have successfully added the atmos folder to Python's path, but you're calling py.moisture.function_name() directly. Since moisture.py is a submodule within the atmos package, Python requires you to reference it through the complete package hierarchy. So, I will suggest following solutions in order of preference

Option 1: Use Full Package Path (Recommended) q = py.atmos.moisture.specific_humidity_from_dewpoint_temperature(P,T)

Option 2: Explicit Module Import py.importlib.import_module('atmos.moisture') q = py.atmos.moisture.specific_humidity_from_dewpoint_temperature(P,T)

Option 3: Fresh MATLAB Session If the above options fail, restart MATLAB to refresh the Python environment: 1. Close MATLAB completely 2. Restart MATLAB 3. Re-execute your setup:moduleDirPath = 'C:\pganguli\Pyscripts\atmos-main\atmos-main\atmos\'insert(py.sys.path, int64(0), moduleDirPath) 4. Try Option 1 again

When you add a package directory to sys.path, Python treats it as a namespace package. Modules within that package must be accessed using dot notation: package.module.function rather than just module.function. So, as quick verification, confirm your package is properly loaded:

py.list(py.sys.path) % Verify your path appears in the list

I will suggest try Option 1 first, it should resolve your issue immediately.

References:

Let me know if you need any clarification!

6 Comments

Hello:
Thanks for the response. I tried with option 1. I did the foll:
q = py.atmos.moisture.specific_humidity_from_dewpoint_temperature(P,T)
But still it shows: No module or function named 'atmos'.
Then I tried the foll:
py.importlib.import_module('atmos.moisture')
Error using <frozen importlib>_find_and_load_unlocked (line 1324)
Python Error: ModuleNotFoundError: No module named 'atmos'
Error in <frozen importlib>_find_and_load (line 1360)
Error in <frozen importlib>_gcd_import (line 1387)
Error in <frozen importlib>_call_with_frames_removed (line 488)
Error in <frozen importlib>_find_and_load_unlocked (line 1310)
Error in <frozen importlib>_find_and_load (line 1360)
Error in <frozen importlib>_gcd_import (line 1387)
Error in __init__>import_module (line 90)

Hi @Poulomi,

I have analyzed your error stack trace, and the persistent ModuleNotFoundError: No module named 'atmos' indicates that my initial approach of correcting the sys.path configuration hasn't resolved the underlying issue. After analyzing your recent error trace:

     Error in <frozen importlib>_find_and_load_unlocked (line 1324)
     Python Error: ModuleNotFoundError: No module named 'atmos'

This specific error signature indicates that Python's import machinery cannot locate the atmos package in its module search path, despite sys.path modifications. This typically occurs when:

1. Package Initialization Failure: Missing or corrupted _init_.py files 2. MATLAB's Python Interpreter State: Cached import failures persisting across attempts 3. File System Permissions: MATLAB's Python subprocess lacking read access 4. Package Structure Malformation: Incorrect directory hierarchy from extraction

So, I will suggest implement a direct module access strategy that bypasses MATLAB's Python package resolution entirely. Execute the following steps in sequence:

Step 1: MATLAB-Python Environment Reset

% Force clear Python interpreter state
clear classes
py.importlib.invalidate_caches();

Step 2: Direct Module Path Configuration

% Target the specific directory containing moisture.py
moistureModulePath = 'C:\pganguli\Pyscripts\atmos-main\atmos-    main\atmos\';
if count(py.sys.path, moistureModulePath) == 0
  insert(py.sys.path, int64(0), moistureModulePath);
end

% Diagnostic verification

fprintf('Python path[0]: %s\n', string(py.sys.path{1}));

Step 3: Standalone Module Import

% Import moisture.py as independent module (not package 
submodule)
try
  py.importlib.import_module('moisture');
  fprintf('SUCCESS: moisture module imported\n');
catch ME
  fprintf('FAILED: %s\n', ME.message);
  return;
end

Step 4: Function Access Verification

% Direct function call bypassing package hierarchy
try
  q =   py.moisture.specific_humidity_from_dewpoint_temperature(P,T);
  fprintf('SUCCESS: Function executed, result type: %s\n',     class(q));
catch ME
  fprintf('FAILED: %s\n', ME.message);
end

Step 5: Module Introspection

% Verify available functions
available_functions = py.dir(py.moisture);
fprintf('Available functions in moisture module:\n');
for i = 1:length(available_functions)
  if ~startsWith(string(available_functions{i}), '__')
      fprintf('  - %s\n', string(available_functions{i}));
  end
end

So, this time by importing moisture.py directly as a top-level module rather than accessing it through the atmos.moisture package path, you circumvent:

  • Python's package discovery protocol
  • Hierarchical import resolution
  • Package initialization dependencies

Please Report Back: Execute each step and provide: 1. Console output from Steps 2-3 (including any error messages) 2. The specific error message if Step 3 fails 3. Results from Step 5 (function listing)

Try this systematic approach and provide precise diagnostic information for further troubleshooting.

Let me know how it goes!

Hi there
I run each of these commands and detailing the output here.
Step 2: The output from step 2 was
Brace indexing into the result of a function call is not supported. Assign the result of
'py.sys.path' to a variable first, then brace index into it.
So, I defined a variable V,
V=py.sys.path
V{1}
ans =
Python str with no properties.
C:\pganguli\Pyscripts\atmos_main\atmos\
After running Step 3, I received the following error message
FAILED: Python Error: ModuleNotFoundError: No module named 'atmos'
The Step4 provided me the following error message:
FAILED: Unable to resolve the name 'py.moisture.specific_humidity_from_dewpoint_temperature'.
After performing Step5, I am receiving the same old error message
No module or function named 'moisture'.
In total, it is still unable to identify the python path properly and fail to make a seemless Python-MATLAB integration. kindly help in this regard. I also tried it in this way:
py.importlib.import_module("C:\pganguli\Pyscripts\atmos_main\atmos\atmos.moisture.py")
Error using <frozen importlib>_find_and_load_unlocked (line 1324)
Python Error: ModuleNotFoundError: No module named
'C:\\pganguli\\Pyscripts\\atmos_main\\atmos\\atmos'
Error in <frozen importlib>_find_and_load (line 1360)
Error in <frozen importlib>_gcd_import (line 1387)
Error in <frozen importlib>_call_with_frames_removed (line 488)
Error in <frozen importlib>_find_and_load_unlocked (line 1310)
Error in <frozen importlib>_find_and_load (line 1360)
Error in <frozen importlib>_gcd_import (line 1387)
Error in <frozen importlib>_call_with_frames_removed (line 488)
Error in <frozen importlib>_find_and_load_unlocked (line 1310)
Error in <frozen importlib>_find_and_load (line 1360)
Error in <frozen importlib>_gcd_import (line 1387)
Error in __init__>import_module (line 90)

Hi @Poulomi,

Thank you for sharing your detailed outputs. I’ve carefully reviewed each of the errors you encountered and want to provide a systematic explanation and resolution. The goal is to ensure MATLAB can call your Python functions seamlessly without further trial-and-error.

1. Brace Indexing Error

Error:

Brace indexing into the result of a function call is not supported.

Root Cause: MATLAB does not allow `{}` indexing directly on the return value of a function. `py.sys.path` returns a Python list object, which must first be assigned to a MATLAB variable.

V = py.sys.path; % assign first disp(V{1}); % then access

2. ModuleNotFoundError: No module named 'atmos'

Error:

FAILED: Python Error: No module named 'atmos'

Root Cause: You added the `atmos` folder itself to `sys.path`. Python expects the *parent directory of the package* in `sys.path`, and modules must be imported using the *full package hierarchy*.

Solution:

parentPath = 'C:\pganguli\Pyscripts\atmos_main\'; % parent folder of 'atmos' if count(py.sys.path, parentPath) == 0 insert(py.sys.path, int64(0), parentPath); end

py.importlib.import_module('atmos.moisture'); % import using full package path

3. Unable to resolve py.moisture.function

Error:

FAILED: Unable to resolve the name 'py.moisture.specific_humidity_from_dewpoint_temperature'

Root Cause: `moisture.py` is a submodule of `atmos`. MATLAB cannot access it directly as `py.moisture`. Python requires functions to be called as `package.module.function`.

Solution:

q = py.atmos.moisture.specific_humidity_from_dewpoint_temperature(P, T);

4. Attempted full path import fails

Error:

py.importlib.import_module("C:\pganguli\Pyscripts\atmos_main\atmos\atmos.moisture.py")

Root Cause: `import_module` only accepts *module/package names*, not absolute paths. Python interprets the string literally and cannot find a module with that name.

Solution: Always import using the package name relative to `sys.path`:

py.importlib.import_module('atmos.moisture');

5. Environment Reset and Diagnostics

To avoid cached import issues:

clear classes py.importlib.invalidate_caches();

Verify that MATLAB sees the path:

V = py.sys.path; disp(V);

List available functions inside `moisture`:

available_functions = py.dir(py.atmos.moisture); disp(available_functions);

Root Cause Summary

1. `sys.path` pointed to the package folder, not its parent. 2. Direct calls like `py.moisture` bypass Python’s package hierarchy. 3. Absolute path imports are invalid in Python. 4. MATLAB caches imports; clearing classes and invalidating caches is required.

Following these guidelines precisely will resolve the errors and enable seamless MATLAB-Python integration.

Yes, I got it now, my calculated q value. But when I ran
available_functions = py.dir(py.atmos.moisture)
The output shows
TypeError: 'moisture' object is not callable.
But I could get the q value after fixing the parent directory and running the script
q = py.atmos.moisture.specific_humidity_from_dewpoint_temperature(P, T)
Thanks a bunch for this help!

Hi @Poulomi,

I am very pleased to hear that you were able to compute the specific humidity successfully after correcting the parent directory path. This confirms that MATLAB and Python are now interfacing properly, and that the package hierarchy is being resolved as intended.

With regard to the TypeError you encountered when executing

   available_functions = py.dir(py.atmos.moisture);

this arises because py.atmos.moisture is treated as a module object, whereas dir should be applied to an explicit Python object reference. A more robust approach is to import the module first and then query its attributes, for example:

moisture_module = py.importlib.import_module('atmos.moisture');
available_functions = py.dir(moisture_module);
disp(available_functions);

This will return the functions, classes, and variables defined within the module. That said, since your primary objective of obtaining the humidity calculation is functioning correctly, this step is primarily diagnostic and not essential for your workflow.

In summary: * The path configuration and import mechanism are now correctly established. * Function calls within the atmos.moisture module execute as expected. * Introspection of available functions can be performed via explicit import followed by dir.

You should now be well-positioned to extend this workflow to other modules within the atmos package.

Sign in to comment.

More Answers (0)

Products

Release

R2024b

Asked:

on 27 Aug 2025

Commented:

on 1 Sep 2025

Community Treasure Hunt

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

Start Hunting!