No module or function named error in Python custom function with MATLAB
You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
0 votes
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:
- MathWorks Documentation: "Call User-Defined Python Module" - Shows how to add modules to Python search path and call functions using py.module.function syntax https://www.mathworks.com/help/matlab/matlab_external/call-user-defined-custom-module.html
- MathWorks Documentation: "Call Python from MATLAB" - Official guide for Python integration https://www.mathworks.com/help/matlab/call-python-libraries.html
- MathWorks Documentation: "Python with MATLAB" - Comprehensive guide for calling Python library functionality from MATLAB https://www.mathworks.com/help/matlab/python-language.html
Let me know if you need any clarification!
6 Comments
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 @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.
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.
More Answers (0)
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)