0

How do I structure subdirectories in a python project, and make the code therein available to other subdirectories within the same project?

Example of what I'm finding difficult:

root/
+--- __init__.py
+--- foo/
     +--- __init__.py
     +--- foo.py
     +--- test/
          +--- foo_test.py

I have tried to use relative imports (as suggested in this SO answer)

In foo_test.py:

#!/usr/bin/python

from ... import foo

Attempting to run this from the command line:

$ chmod +x ./foo_test.py
$ ./foo_test.py

I get the following error:

Traceback (most recent call last):
  File "./foo_test.py", line 3, in <module>
    from ... import foo
ValueError: Attempted relative import in non-package

Question:

What is the pythonic way to make foo available to foo_test and other subdirectories which sit alongside foo?

Steve Lorimer
  • 27,059
  • 17
  • 118
  • 213
  • It's all explained in that question, but in essence the problem is that you're not supposed to have an executable file in a package. Packages are intended to be libraries, not executable programs. – Aran-Fey Mar 26 '18 at 12:25
  • @Aran-Fey thanks for the comment! My experience of python is rudimentary at best - typically only single scripts. I'm "progressing" to something a bit larger, so want to structure my code into multiple scripts split over several directories etc. Some will be executable. Others will be libraries. What is the pythonic way to structure my project in this case? – Steve Lorimer Mar 26 '18 at 15:59
  • 1
    I'm really not an authority on the topic, but I think you have two options: 1) Design your package to be a pure library, and put all the executable scripts outside of the package. 2) What I said earlier was a bit misleading: You can design a package to be executable, but you can't have an executable _script_ inside of a package. So the other option is to make a package for each feature, and make the packages executable by adding a [`__main__.py` file](https://stackoverflow.com/questions/4042905). 3) Drop by the [python chatroom](https://chat.stackoverflow.com/rooms/6/python) to ask experts :) – Aran-Fey Mar 26 '18 at 16:45
  • @Aran-Fey thanks for the input, much appreciated – Steve Lorimer Mar 26 '18 at 16:49

0 Answers0