1

I've looked at most every link regarding relative imports and especially those with regard to top-level-packages, but I'm still having a ton of trouble getting my relative import code to work. For reference, I'm using Python 3.6.

I have a directory of tests that I want to run, isolated in their own directory, tests. I want to import all of the modules package into one file called InputTests.py. Here is the format of my project directory.file directory

Within InputTests.py, I attempt to import modules this way:

from .. import modules

I get the error:

File "/Users/wfehrnstrom/Desktop/meeting_minutes/tests/InputTests.py", 
line 2, in <module>
from .. import modules
ValueError: attempted relative import beyond top-level package<code>

However, I'm using the command: python -m tests.InputTests, which supposedly tells the interpreter to run everything from my top level directory. So I guess my question is, why does my relative import statement not work given the fact that I am running this from the package above. This stack overflow post seemed to detail what I need, but their solution, running with -m doesn't work for me: How to do relative imports in Python?

In addition, there seems to be a contradiction to this in this stack overflow post: Relative importing modules from parent folder subfolder

The latter post seems to suggest that the contextual meaning of .. and . do not change based on where you execute your Python command, however the former says that it does. This has me extremely confused. Can anyone both clarify relative imports and resolve this discrepancy? Thank you.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
wfehrn
  • 105
  • 1
  • 11

1 Answers1

0

I can only try to answer your question for Python 2.7 but I hope this is helpful anyways.

PEP 328 which is quoted in the answer to "How to do relative imports in Python?" you linked is partwise outdated since it suggests importing based on the __name__ of the module which would be __main__ for the main script and therefore prevent using relative imports in that module at all even when using -m.

PEP 366 solved this by introducing the __package__ attribute.

When you use python -m tests.InputTests the value of the __package__ in InputTests.py will be tests. This does not allow importing from parent packages since tests is the current and top-level package.

Running python -m modules.tests.InputTests in the directory "meeting_minutes" should solve that.

Marcono1234
  • 5,856
  • 1
  • 25
  • 43