开发者

Relative imports from __init__ in multi-file Django apps

I have a Django project located at /var/django/project/ where /var/django/ is in the PATH

within that project I have:

___init__.py
manage.p开发者_运维百科y
utils/
    __init__.py
    tools.py

utils/__init__.py contains a function named get_preview

utils/tools.py contains a function named get_related

How can utils/__init__.py import get_related from utils/tools.py?

How can utils/tools.py import get_preview from utils/__init_.py?

I have tried relative imports as well as static imports but seem to get an error in tools.py when I try to from project.utils import get_preview


Yeah, this is bad structure. You gotta watch out here with creating a circular import between the two files. About circular imports.


You can't (and shouldn't). You are structuring your code very poorly if files in your module are referencing code in the __init__.py associated with it. Either move both functions into __init__.py or both of them out of __init__.py or put them into separate modules. Those are your only options.


You can do it, you just need to make one of the imports happen at runtime to avoid the circular import.

For example, __init__.py:

from project.utils.tools import get_related

def get_preview():
     # ...

and tools.py:

def get_related():
    from project.utils import get_preview
    # ...
    get_preview()
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜