python-3.xpython-import

ModuleNotFoundError: cannot import local file


I have a module with multiple files structured like this:

/bettermod/
├── __init__.py
├── api.py
├── bettermod.py
├── errors.py
└── loggers.py

From bettermod.py, I'm trying to import two things:

For the first thing, it is quite easy, I just have to do this:

from .api import API

However, for importing the whole errors.py file, I'm encountering a problem; I'm trying to do like this:

from . import errors

which should work, according to this python documentation, but it's raising the following error:

  File "/path/to/bettermod/bettermod.py", line 10, in <module>
    from . import errors
ModuleNotFoundError: No module named 'bettermod'

Edit: when debugging, I found that __name__ was equal to bettermod.bettermod


Solution

  • From docs:

    Note that relative imports are based on the name of the current module.

    I cannot tell you what is wrong with certainty, but there is a smell: bettermod package has a bettermod module. You want to do from bettermod.bettermod import MyBetterClass? I doubt it. In Python files ARE namespaces, so choosing your file and directory names is also an API design. Just keep that in mind.

    I suspect the problem is masked by the name collision. Try this. If you run python in bettermod directory and say import bettermod you are importing bettermod\bettermod.py. And . is relative to the bettermod.py module. Now try to run python in directory above bettermod package directory. It will work because now . resolves to bettermod package.

    Try:

    import mymodule
    mymodule.__file__
    

    This will tell what mymodule is. For packages, it will show path to __init__.py. This will help you to orient yourself. Also look up PYHTONPATH and how you can use it to make sure you are importing from the right path.