I’m currently importing a function from a .py file I wrote with the following code.
import sys
from pathlib import Path
resource_dir = str(Path("MyTools.py").resolve().parent.parent) + '\\resources'
if resource_dir not in sys.path:
sys.path.insert(0, resource_dir)
from MyTools import generate_random_password
This works but gives a warning since it can’t see ‘MyTools’ until runtime. I figure there is probably a better way to do this while maintaining the folder structure.
I know I could just add a path to the PYTHONPATH system vars, but am looking for an in-script solution.
Mostly looking forward to learning more Python, so if the system var is the correct way to do this I would be interested why it’s the ‘proper’ way and/or why what I’m currently doing is not optimal (honestly the yellow warning is just annoying to me but seems to work fine otherwise).
otherwise you lose current working directory independence and the cross platform filename manipulation that pathlib is supposed to provide.
But either way, really the answer to all how can I make this unorthodox project layout work questions is to stop fighting the language and use a normal layout.
Thanks for the reply. I’ll try updating my code and see what that does.
As far as fighting the language, I’m not really trying to fight the language. My end goal is to have only one copy of MyTools.py, not one in each project. That way if I need to make changes, I make changes to one place, not 20+ places.
Is there a particular reason you are looking for in-source approach? Asking because that is about the hardest way to get correct and stable because it ultimately depends on the current directory when the program starts.
To make your code reusable I recommend the flat layout and make it into a package. Then you can install it into any venv, or once globally and use it across your projects. This way it will work from anywhere and does not depend on your program finding out where to look.
Thanks for the reply and the link. I’m going to read over the link tonight. While I like the directory structure I’m using from an organizing standpoint, I REALLY did not like how delicate it makes the imports. I’m hoping the link describes a nice structure that isn’t just place all files for all similar projects in one folder.
You can use a monorepo structure if you really don’t want to duplicate code, but the most idiomatic solution is to make them separate packages and make the two projects each depend on the tool.