Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug Python import failure

I have a directory structure:

network/__init__.py
network/model.py
network/transformer/__init__.py
network/transformer/t_model.py

both __init__.py files have appropriate

__all__ = [
    "model",  # or "t_model" in the case of transformer
    "view",
    ]

In t_model.py, I have

from .. import model

but it says:

ImportError: cannot import name model

If I try

from ..model import Node

it says:

ImportError: cannot import name Node

These are very confusing errors.


Edit: Even an absolute import fails:

import network as N
print(dir(N), N.__all__)
import network.model as M

['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'transformer'] ['model', 'view']
Traceback (most recent call last):..........
AttributeError: 'module' object has no attribute 'model'

Edit: It was a circular import.

like image 429
Neil G Avatar asked May 26 '11 05:05

Neil G


1 Answers

This works for me. Can you run/import model.py? If it has syntax errors you can't import it. (In general I recommend not to do relative imports, the use of them is limited).

Your absolute import is very confusing. The way to do an absolute import in this package is:

from network model import Node

This works fine.

I have a program.py in the top level (above network):

from network.transformer import t_model

And the t_model.py looks like this:

from .. import model
print "Model", model

from ..model import Node
print "Node", Node

from network.model import Node
print "Absolute", Node

And the output is:

Model <module 'network.model' from '/tmp/network/model.pyc'>
Node <class 'network.model.Node'>
Absolute <class 'network.model.Node'>

So as you can see it works fine your error is somewhere else.

like image 114
Lennart Regebro Avatar answered Oct 16 '22 04:10

Lennart Regebro