简体   繁体   English

python中的循环模块依赖性

[英]Circular module dependency in python

I have two modules, baselib.Database and baselib.Application. 我有两个模块,baselib.Database和baselib.Application。 In baselib.Application, I have 在baselib.Application中,我有

import baselib.Database

APP = None
class BaseApplication():
    def __init__(dbClass = baselib.Database.GenericDb...):
        global APP
        this.dbClass = dbClass
        APP = this
        etc...

In baselib.Database, I have 在baselib.Database中,我有

import baselib.Application

def getDB(dbClass = baselib.Application.APP.dbClass):
    etc...

class GenericDB():
    def __init__(self, args):
    etc...

The problem is, when I import either of these modules, I get 问题是,当我导入这些模块中的任何一个时,我都会

AttributeError: 'module' object has no attribute (modulename)

The problem seems to stem from the fact that the default arguments are evaluated during the import; 问题似乎源于在导入过程中评估默认参数的事实。 if I replace getDB with 如果我将getDB替换为

def getDB(dbClass = None):
    dbClass = dbClass or baselib.Application.APP.dbClass

and do the same thing with the other default argument, everything works fine. 并使用其他默认参数执行相同的操作,则一切正常。 Is this the best/most pythonic way to do this, or should I just avoid the circular dependency entirely and combine the two modules into one file? 这是执行此操作的最佳/最有效的pythonic方式,还是应该完全避免循环依赖并将两个模块合并为一个文件? I'd really like to keep them separate because a large part of my codebase is dependent on them. 我真的很想将它们分开,因为我的代码库很大一部分都依赖于它们。

I think this http://effbot.org/zone/import-confusion.htm#circular-imports may answer your question. 我认为这个http://effbot.org/zone/import-confusion.htm#circular-imports可能会回答您的问题。 Basically, import is also a statement. 基本上,导入也是一个声明。 We should avoid circular module dependency. 我们应该避免循环模块依赖性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM