I was writing this, and then I realized many people had this same issue and many 'workarounds' were given, but I haven't seen one that is really satisfactory.
This answer got 1000 upvotes, but it doesn't work for me (I suppose it's for python 2).
This one also has many upvotes, but most of the solutions simply don't work for this layout, or it's super complicated.
Anyway, given this file structure:
folder/
mylib/
__init.py__
MyClass.py
src/
main.py
init.py
MyClass.py:
class MyClass:
def __init__(self):
self.x = 0
main.py
# import sys
# sys.path.append('.') # Only works if I have this!
from mylib.MyClass import MyClass
m = MyClass()
print(m.x)
Running python src/main.py
from the root folder/
gives:
ModuleNotFoundError: No module named 'mylib'
The easist solution I found is modifying sys.path
(uncommenting the code above), but it still feels a bit hacky. Alternatively, if main.py
is on the root folder it also works, but I don't want to have dozens of files cluttering the root directory.
This answer says that "one should structure the files into packages", but doesn't say how that is done. Is there still no better alternative?