Sunday 12 May 2019

python - How to import package properly




I have some projects I try to split up for easier management. Therefor I moved some parts that are used by different applications into modules rather than copying files around.



Right now I have the following structure for my modules (every module has its own docs and tests):



/projects
/module1
__init__.py
run_tests.py
/docs

...
/module1
__init__.py
module1.py
/tests
__init__.py
module1_test.py
/module2
...



Now I got myself the "main app" directory laid out in the same manner:



/projects
run_app.py
run_tests.py
/docs
...
/app
__init__.py

app.py
module1 <-- Link to the module1 repository
/tests
__init__.py
app_tests.py


All my __init__.py files are empty at the moment and I do not know how to write a proper import statements in my app.py file. Since there is only one class in module1 I don't want a hugh import module1.module1.module1.ModuleClass so the ModuleClass should be imported to "module level" so I can just do something like a import module1.ModuleClass. I figure I have to tweak the __init__.py files but all I tried broke either the tests or the whole import.



Any help would be very much appreciated and sorry for my poor explanations I am not a native speaker...



Answer



Ok, I found the solution myself. As always it was pretty straight forward.



I just had to add the following line in all the __init__.py files recursively to the top of the module.



from .module1 import ModuleClass


I will leave this here for future references if somebody might end up in the same situation.




Cheers


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...