MATLAB Answers

Unrecognized python functions when using same-module imports from a custom package

조회 수: 1(최근 30일)
Daniel Bronstein
Daniel Bronstein 2021년 8월 2일
댓글: Daniel Bronstein 2021년 8월 5일
I am unable to get MATLAB to recognize functions within my custom python module if the file is importing anything from another module within the same package.
File Structure:
python_test_lib
| __init__.py
| file_a.py
| file_b.py
file_a.py content:
class ClassA:
def __init__(self, num):
self.num = num
file_b.py content
from file_a import ClassA
def function_b():
ca = ClassA(3)
print(f'My class A: {ca.num}')
In this toy example, the package is partially imported such that ClassA is available through the interperter via
py.python_test_lib.file_a.ClassA()
But no functions from file_b.py are available. Attempting access yields:
py.python_test_lib.file_b.function_b()
--------------
Unable to resolve the name py.python_test_lib.file_b.function_b()
I've tried various syntaxes for the import statement including
import ClassA
from .file_a import ClassA
from python_test_lib.file_a import ClassA
import file_a

답변(1개)

Shadaab Siddiqie
Shadaab Siddiqie 2021년 8월 5일
From my understanding you want to call python functions in the matlab code. You can do this by setting python path and calling functions as follows:
Set up Python and Python path
pyversion
pathToFile = fileparts(which('file.py'));\
if count(py.sys.pathToSpeech) == 0
insert(py.sys.path,int32(0),pathToFile);
end
call python function
pyOut = py.file.function_name(inputs to the function)
  댓글 수: 1
Daniel Bronstein
Daniel Bronstein 2021년 8월 5일
The python path is already set appropriately. As I said, I am create an instance of ClassA through the interperter. However, function_b is not available and I believe that is due to the fact that it is importing from file_a within the same package. My question is what is the appropriate syntax/file layout to be able to handle these inter-package imports?
If you try setting up the files exactly as described the problem should be evident

댓글을 달려면 로그인하십시오.

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by