What is the * easy * way to structure a python project?

So, I have this python thing that should handle the file.

At first it was:

my_project/ ├── script.py 

And I just run it with python script.py file.csv .

Then he grew and became:

 my_project/ ├── script.py ├── util/ │ └── string_util.py ├── services/ │ └── my_service.py 

(Each directory has an empty __init__.py )

But now my_service.py would like to use string_util.py , and it is not so simple just how to do this. p>

I would like to do from ..util import string_util in my_service.py (which is imported into script.py using from services import my_service ), but this does not work with python script.py , since my_service __name__ now only services.my_service (and I get Attempted relative import beyond toplevel package )

  • I can do cd .. and python -m my_project.script , but it seems so unnatural, and it would be very difficult to put it in README for instructions on how to run it.

  • Now I solve it with an ugly hack sys.path.append() .

What other options do I have?

+7
python module package python-import project-structure
source share
1 answer

It borders on an opinion, but I will share it.

You should look at your project differently. Select one control point and specify your import there to avoid all the odd relative imports that you are trying to get around. So, looking at your project structure:

 my_project/ ├── script.py ├── util/ │ └── string_util.py ├── services/ │ └── my_service.py 

As you are doing now, execute your code from my_project . Therefore, all of your imports should be in relation to this point. Therefore, your import looks like this:

 # my_service.py from util.string_util import foo 

Another way to think about this is that if you are moving your project or using CI, you need to make sure that you specify which project root you want to run from. Keeping these things in mind and indicating a single point of execution at which your project should be executed, your life will be greatly simplified when it comes to structuring your packages and modules and referencing them accordingly, allowing other systems to use your project correctly without having to deal with odd relative imports.

Hope this helps.

+2
source share

All Articles