1

I have a package (or what I think should be a package) with a directory structure:

Switch/
    tests/
        testing.py
    Sw.py
    #otherfiles

I am trying to import Sw.py from testing.py. I have tried several things, including from .. import Sw, import ..Sw, from Switch import Sw and several other variations. I have tried these with and without and __init__.py file in the Switch directory and in the tests directory. The primary error I'm getting is:

Traceback (most recent call last):
  File "tests/testing.py", line 10, in <module>
    from .. import Sw
ImportError: attempted relative import with no known parent package

Though I also get syntax errors when I try import ..Sw and ModuleNotFoundError: No module named 'Switch' when I try from Switch import Sw.

I have done my best to ensure none of the directories in the package are in the path or pythonpath, though I am on WSL running Python installed on Windows, so the paths are somewhat complex.

When I go to the directory above Switch and run python -c "import Switch.Sw" it works correctly, but inside the Switch directory it responds with ModuleNotFoundError: No module named 'Switch'

RedKnite
  • 1,525
  • 13
  • 26

2 Answers2

1

Use this code to go up a directory and then you should be able to import from your package

import os, sys
dir_path = os.path.dirname(os.path.realpath(__file__))
parent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))
sys.path.insert(0, parent_dir_path)

I know it's cumbersome but I'm not sure if there's a better solution.

Luke-zhang-04
  • 782
  • 7
  • 11
0

I figured out the problem was that I was running the file as a script or my command as a script. python -c "import Sw" treats "import Sw" as a script which is why relative and absolute imports weren't working. It wasn't treating Sw as part of a package, just a standalone module. This Question cleared things up for me. I should have been doing python -m Switch.Sw.

RedKnite
  • 1,525
  • 13
  • 26