Custom Python module not importing

2019-09-02 17:29发布

问题:

I can't seem to get past this and do not quite understand what is happening. I have a directory with two class files in it. Using the REPL from within that directory I can import both files and execute their logic. From their parent directory which main() is ran from however, only one class file is visible, pagetable.

The project structure is currently,

project/
    src/
        __init__.py # empty
        pagingsimulation.py # main() imports memory
        process.py
        memory/
            __init__.py # imports pagetable.py
            pagetable.py # visible
            page.py # error

pagingsimulation.py was able import memory/ and instantiate pagetable.PageTable, but once I created page.py and had pagetable.py import page.py, pagingsimulation.py now throws this error upon execution.

Traceback (most recent call last):
  File "pagingsimulator.py", line 5, in <module>
    import memory
  File "src/memory/__init__.py", line 1, in <module>
    from .pagetable import PageTable
  File "src/memory/pagetable.py", line 1, in <module>
    import page
ImportError: No module named 'page'

within memory/__init__.py I currently have,

    from .pagetable import PageTable

...but have tried many other variations without success.

I've tried multiple approaches and have researched this for awhile and perhaps it is something I just cannot see at this point. What is preventing my custom modules from importing each other when ran from main()?

回答1:

The solution as I suspected was a pathing issue and more specifically in relation to how the modules interact once imported into the parent file, pagingsimulation.py.

So to resolve this issue it had nothing to do with __init__.py but rather how I was accessing page.py from within pagetable.py

So pagingsimulator.py uses,

import memory

And within memory, the init.py file has,

from .pagetable import PageTable

For PageTable to access Page, the import statement had to be,

from memory import Page

It seems a bit funky to me and after failing so many times I would like to say there is a cleaner way to do this, but for the time being I'll take my win and hope that leaving this question here benefits someone else as I was unable to find something similar during my search.