Search code examples
pythonpydev

Python refuses to import a module


There are three modules in question, in two packages:

Tools
   BasicLogger.py
   CascadingDataSet.py

Sandbox
   test.py

BasicLogger.py contains a class ('BasicLogger'), with no parents other than 'object'.

CascadingDataSet.py contains a class ('CascadingDataSet'), which is a child of BasicLogger, above.

test.py imports CascadingDataSet as follows:

import Tools.CascadingDataSet.CascadingDataSet as CascadingDataSet

(As a side note, I'm convinced I'm doing that wrong, but not only does it usually work, I can't seem to find a way to do that without repetition somewhere. Also, it appears to be working here.)

CascadingDataSet.py imports BasicLogger as follows:

import Tools.BasicLogger.BasicLogger as BasicLogger

This where it fails, and this is the error that I get.

Traceback (most recent call last):
  File "D:\code\python\Engine\SandBox\test.py", line 7, in <module>
    import Tools.CascadingDataSet.CascadingDataSet as CascadingDataSheet
  File "D:\code\python\Engine\Tools\CascadingDataSet.py", line 7, in <module>
    import Tools.BasicLogger.BasicLogger as BasicLogger
ModuleNotFoundError: No module named 'Tools.BasicLogger.BasicLogger'; 'Tools.BasicLogger' is not a package

I have tried:

  • renaming the class and filename for BasicLogger. No success.
  • renaming the package itself. No success.
  • moving BasicLogger.py to a different package. No success.
  • instantiating an object of the BasicLogger class inside BasicLogger.py. This was successful, but only confuses me more, because obviously the code itself is fine.
  • creating an entirely new file, with a different name, copying the contents of BasicLogger.py into it, and trying to import that.
  • importing BasicLogger directly into test.py. Nope.
  • closing and reopening the IDE. Had to try.

My IDE (pyDev for eclipse) completely recognizes the file as an appropriate import; I even erased the import line and redid it letting pyDev autocomplete each part. As I mentioned, the code copies fine-- but its obviously something in the code. Either that, or I fundamentally do not understand imports at all, but I've been playing with python for like, a year, and this has never come up.


Solution

  • I have got it working. In two ways:

    Two solutions:

    This one was posted by deceze in the comments.

    from Tools.BasicLogger import BasicLogger
    

    This is doubly helpful because it not only solves this problem, but avoids the ridiculous threepeat, and is considerably more compact and elegant than:

    import Tools.Logging as Logging
    
    class CascadingDataSet(Logging.BasicLogger):
    
    

    I'm still baffled about why it worked for CascadingDataSet but not BasicLogger, but I'm just going to let that go.