Handle circular dependencies in Python modules?

前端 未结 3 517
误落风尘
误落风尘 2020-12-06 07:51

this is a case again where I\'m running around in circles and I\'m about to go wild.

I wish Python would analyze all files at first, so that it would know all identi

3条回答
  •  被撕碎了的回忆
    2020-12-06 08:33

    If you can't avoid circular imports, move one of the imports out of module-level scope, and into the method/function where it was used.

    filea.py

    import fileb
    
    def filea_thing():
        return "Hello"
    
    def other_thing():
        return fileb_thing()[:10]
    

    fileb.py

    def fileb_thing():
        import filea
        return filea.filea_thing() + " everyone."
    

    That way, filea will only get imported when you call fileb_thing(), and then it reimports fileb, but since fileb_thing doesn't get called at that point, you don't keep looping around.

    As others have pointed out, this is a code smell, but sometimes you need to get something done even if it's ugly.

提交回复
热议问题