0

I want to structure classes and methods using a subfolder structure as follows in Python 3.8

supermodule/
|_module1/
| |_module1.py (depends on module2)
|_module2/
| |_module2.py (depends on module3)
|_module3/
| |_module3.py
|_scripts/
  |_script1.py (depends on module1, module2, module3 methods)

I was hoping someone could explain how to overcome import errors, and how one could go about coding supermodule like this? Thanks

MKF
  • 105
  • 7

1 Answers1

1

You need to place an empty __init__.py file in each of the module folders. What is __init__.py for?

  • 1
    Thanks, but that should be redundant in python3 because each folder is treated as a module if I'm not mistaken? – MKF Jul 06 '20 at 20:41
  • When importing the error says `ValueError: Attempted relative import in non-package`, even with the `__init__.py` in each directory – MKF Jul 06 '20 at 20:42
  • In both Python 2 and Python 3, the presence of `__init__.py` is what makes a folder into a package. Regarding your error, that's an issue with your code, which you haven't shown in the question. – chepner Jul 06 '20 at 20:44
  • OK thanks. is it possible to run a script in a different directory from the packages, just like in the example above? – MKF Jul 06 '20 at 20:47
  • Yes, but for that I do belive you'd have to set the sys path. [link](https://stackoverflow.com/questions/4383571/importing-files-from-different-folder) – Alexandre Xavier Jul 06 '20 at 20:55