Dan Chrostowski
Dan Chrostowski

Reputation: 347

Why won't my class import in Python?

Edit: __init__.py files are included, but I'm using Python 3 - I don't think it matters.

Another edit: Anything in config.py will import with no problem. If I simply omit from cache import Cache then no errors. Interestingly, no errors occur when importing Config in config.py

I cannot figure out what's wrong here. I'm getting an error whenever I try to import a specific class. Here's what my project layout looks like:

app/
    dir1/
        config.py
        cache.py
        manager.py
        __init__.py
    test/
        test.py
        __init__.py

cache.py:

import sys
import os
sys.path.append(os.path.dirname(__file__))
from manager import Manager, AnotherClass
from config import Config

manager.py

import sys
import os
sys.path.append(os.path.dirname(__file__))
from config import Config
from cache import Cache

test.py

cwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.abspath(os.path.join(cwd, os.pardir)) + '/dir1')
from cache import Cache, AnotherClass
from manager import Manager
test = Cache()
...

So when I run test.py I get this:

File "/path/to/project/app/dir1/<module>
from cache import Cache

ImportError: cannot import name 'Cache'

from manager import Manager line 5, 

Even though config.Config loads just fine, no errors there, but as soon as I try to import cache.Cache it suddenly can't find or import any class in cache.py. All files have the same permissions. Can someone tell me what's wrong here?

Upvotes: 0

Views: 348

Answers (1)

Nils Werner
Nils Werner

Reputation: 36757

You are missing the __init__.py file in your module

app/
    __init__.py
    dir1/
        __init__.py
        config.py
        cache.py
        manager.py
    test/
        test.py

and instead of messing with sys.path should do a relative import like

from .config import Config
from .cache import Cache

Python 2 may also need a line

from __future__ import absolute_import

before those imports.

Upvotes: 3

Related Questions