0

Asking this question here because I've searched for the answer more than a few times and have yet to properly resolve it.

Let's say that I have a program folder structure that looks like this:

src/  
    tests/  
        test1.py  
    code/  
        __init__.py  
        moduleA.py  
        moduleB.py 

and moduleA.py contains a function my_function(x) that I'd like to call from test1.py. __init__.py is an empty file.

What is the appropriate way to access this function?

So far I've tried:

# In test1.py
from code import moduleA
moduleA.my_function(1)

Which results in the following error: ModuleNotFoundError: No module named 'code'

# in test1.py
from .code import moduleA   # or: "from ..code import moduleA"
moduleA.my_function(1)

But this results in the following error: ImportError: attempted relative import with no known parent package

I'd really like to avoid modifying the path or adding extra function calls besides these import lines. Is there a good reason that I'm unable to step through the folder tree using . as appropriate?

Thank you!

  • For `test1.py`, it should indeed be `from ..code import moduleA`; using `.code` gets the path wrong, and using `code` asks for absolute import instead (which won't work because `code` isn't a top-level package). For the actual error message, see the linked duplicate. "Is there a good reason" It's up to you what you consider "good"; but the short version is that the `.`s refer to the **package hierarchy, not** the file system; Python needs the `src` folder to be a package root, which (in the absence of `sys.path` hacks) depends on *how the code is run*. – Karl Knechtel Oct 15 '22 at 04:21
  • (It is on my to-do list to contribute an answer there to approach the problem from a more pedagogic angle.) – Karl Knechtel Oct 15 '22 at 04:46
  • _"the `.`s refer to the package hierarchy, not the file system"_ and _"Python needs the `src` folder to be a package root, which (in the absence of `sys.path` hacks) depends on how the code is run"_ are exactly the "good" answers I was looking for, thank you for your help! Resolved the issue by adding a small function to modify the path and ensuring that I was executing the tests from the correct folder. – freestatelabs Oct 15 '22 at 16:43

0 Answers0