0

I have a directory structure like:

File Structure

In main.py, I try import classes.class1, and then in class1.py I try import class2.

When I run class1.py directly, it imports class2 successfully. However, when I try to run main.py instead, I get an exception that says ModuleNotFoundError: No module named 'class2'.

It seems like the main module cannot see class2. I can't understand the error. Shouldn't it be class1 that is importing class2, not main?

How can I fix the problem?

I thought that when a file was imported, it would see the file that would be in its directory, rather than having to rely on the .py file that calls the function from another directory.

I also tried the approach described in Importing a file that imports another file, but then I get an error that says ImportError: attempted relative import with no known parent package.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
PatzEdi
  • 1
  • 3
  • Create a file name ```__init__.py``` in classes directory (folder). – Maxwell D. Dorliea Feb 06 '23 at 05:45
  • Hello, thanks for the quick reply. I tried doing that, but it still gives me the error. I created an __init__.py as told to. However, am I supposed to leave that blank? – PatzEdi Feb 06 '23 at 05:49
  • @MaxwellD.Dorliea no, that has **nothing to do with the problem**. This is a very common piece of misinformation. – Karl Knechtel Feb 06 '23 at 05:49
  • OP: when you try running `main.py`, what is the current working directory? Exactly what command do you use? Similarly for `class1.py`. Do you see how this is relevant to the problem? – Karl Knechtel Feb 06 '23 at 05:50
  • @KarlKnechtel I see, yes. However, I tried putting an init .py and it seems to be working now. – PatzEdi Feb 06 '23 at 05:52
  • Questions about `import` in Python are asked constantly, and the canonicals are a mess that are not helpful for new users even though immense effort has been put into them and even though the concepts are really not that hard. It would be better if we could start them all over (and I am sort of trying to organize that effort). In the mean time, use the relative import described in the question you found, and then see the duplicate I linked to fix it (or at least, to understand what you changed such that it works now. I guarantee `__init__.py` has nothing to do with it). – Karl Knechtel Feb 06 '23 at 05:56
  • Unless, of course, are using an ancient version of Python (3.2 or earlier). See https://stackoverflow.com/questions/448271/what-is-init-py-for. – Karl Knechtel Feb 06 '23 at 05:59
  • @KarlKnechtel ohh. You are right! Just using the relative import works fine!!! I wonder why it did not work before when It tried it, mustve been doing something wrong. Thanks!!!! – PatzEdi Feb 07 '23 at 00:07
  • Most likely for one of the reasons explained in the linked duplicate. – Karl Knechtel Feb 07 '23 at 00:20

0 Answers0