How to access Python enum in Matlab

15 ビュー (過去 30 日間)
Philipp
Philipp 2025 年 5 月 5 日
回答済み: Philipp 2025 年 5 月 15 日
Hello,
I am implementing an interface to a Python module, that uses various custom enum types that are defined like this:
class EnumName(enum.Enum):
FIRST = firstvalue
SECOND = secondvalue
THIRD = thirdvalue
In my Matlab Code, I need to be able to call python functions that take for example FIRST as input, like this:
obj.function(py.moduleName.EnumName.FIRST)
But when I try this, I get this error:
'EnumName' in module 'moduleName' unrecognized.
Something similar was discussed here, but the error message is different, and the solution does not help in my case, because the values in my case are not strings, so I can't just pass them to the function.
I hope someone can help me. Thanks!

回答 (3 件)

TED MOSBY
TED MOSBY 2025 年 5 月 6 日
Hi Philipp,
As I have limited information about your code and code files, it will be difficult to give an exact solution ence you can try the following workarounds:
  1. Assuming your file name having the code below is named "testFile":
class EnumName(enum.Enum):
FIRST = firstvalue
SECOND = secondvalue
THIRD = thirdvalue
Then this: py.moduleName.EnumName should be modified to py.moduleName.testFile.EnumName
2. Try the installing python again with --enable-shared option if not done earlier. This allows MATLAB to interact with python properly. Please go through this MATLAB answer for more detail:
3. Please go through the entire discussion thread and all answers of this MATLAB answer and try the workarounds suggested here: https://www.mathworks.com/matlabcentral/answers/487329-unable-to-resolve-the-name-py-module?s_tid=answers_rc1-2_p2_MLT
Feel free to reply back here if these does not resolve the error along with all your code files, file names and directory structure.
Hope this helps!

Gayathri
Gayathri 2025 年 5 月 7 日
Hello @Philipp,
I am guessing that the python file with the "Enum" class is stored with the name "moduleName.py".
Please import the python module to MATLAB using the following command.
mod=py.importlib.import_module('moduleName');
We can then use this "mod", python module to access the members of "Enum" class as follows
EnumNames = mod.EnumName;
And then to get the values associated you can use the following command.
first_val = mod.EnumName.FIRST;
py.getattr(first_val, 'value');
I hope this helps!

Philipp
Philipp 2025 年 5 月 15 日
Thanks to both of you for the answers!
I found out that the issue was something different:
MATLAB apparently blocks access to Python submodules starting with an underscore, which the submodule defining the enums had.
I edited the init python file to export the enums directly, and that works now!

カテゴリ

Help Center および File ExchangeCall Python from MATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by