开发者

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.


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.


From this question.

project/
    program.py           # entry point to the program
    network/         
        __init__.py
        transform/       # .. will target network
            __init__.py

I think you can also execute network/model.py from the directory below and get relative imports to network. so...

network/
    model.py
    __init__.py

then you would start the program with $ python network/model.py. You may or may not need to hit __init__.py instead. I had an app engine program that targeted module/__init__.py and relative imports worked great.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜