开发者

How to import __init__'s method in inner module?

My structure of file is

foo/
   __init__.py
   bar.py

file __init__.py

def abc():
    print 'ABC'

file bar.py

from foo import abc

I got this error.

Traceback (most recent call last):开发者_StackOverflow
   File "foo/bar.py", line 1, in <module>
   from foo import abc
ImportError: No module named foo


Use a relative import (requires Python 2.6 or greater):

from . import abc


Importing foo like that should work, but you need to ensure that the directory above foo is on the Python path. You can check what is on the path by printing sys.path.

If you give us more details on how you're running your code, including a full traceback on the error I can help more, but the basic advice is to check the Python path is correct.


When importing the package, Python searches through the directories on sys.path looking for the package subdirectory. That means thatfoomust be a subdirectory of one of the directories in thesys.pathlist. Sincebar.pyis itself in thefoodirectory, one way this could be accomplished would be for it to add its parent folder to sys.path like this (assumingfoois the current working directory when it's executed):

import sys
sys.path.append('..')  # add parent folder

from foo import abc


This one worked for me, even if bar.py was imported in __init__.py:

from .__init__ import abc

There is one tiny downside of this though. When abc is type hinted, it will be noted in helps as foo.__init__.abc instead of foo.abc. As a workaround, this case I use string type hints like def somefunc() -> 'foo.abc':.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜