Pythonic way to resolve circular import statements?

爷,独闯天下 提交于 2019-11-28 04:41:12
ebo

Resolving these constructs usually involves techniques like Dependency Injection.

It is, however, rather simple to fix this error:

In calendarLib.py:

import homePageLib

class CalendarPage(object):
    def clickHomePageLink(self):
        [...]
        return homePageLib.HomePage()

The code at module level is executed at import time. Using the from [...] import [...] syntax requires the module to be completely initialized to succeed.

A simple import [...] does not, because no symbols are accessed, thus breaking the dependency chain.

Kashif Siddiqui

Please read Sebastian's answer for detailed explanation. This approach was proposed by David Beazley in PyCon

Try positioning the imports on the top like this

try:
    from homePageLib import HomePage
except ImportError:
    import sys
    HomePage = sys.modules[__package__ + '.HomePage']

This will try to import your HomePage and if failed, will try to load it from the cache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!