How to access Python enum in Matlab

13 views (last 30 days)
Philipp
Philipp on 5 May 2025
Answered: Philipp on 15 May 2025
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!

Answers (3)

TED MOSBY
TED MOSBY on 6 May 2025
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 on 7 May 2025
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 on 15 May 2025
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!

Tags

Community Treasure Hunt

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

Start Hunting!