Pythonic way to resolve circular import statements?

后端 未结 2 1411
花落未央
花落未央 2020-12-04 18:01

I just inherited some code which makes me uneasy: There is a testing library, full of classes corresponding to webpages on our site, and each webpage class has methods to a

相关标签:
2条回答
  • 2020-12-04 18:25

    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

    0 讨论(0)
  • 2020-12-04 18:30

    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.

    0 讨论(0)
提交回复
热议问题