使模块部分导入

Making a module partially imported

我有一个包含几个模块 configlogging(以及其他模块)的包。

logging模块提供了一个方法来记录包的日志文件(在config模块中定义)。

config 模块包含一堆静态配置值(硬编码)以及一些从文件加载的动态配置值。

mypackage/logging.py

import mypackage.config

def log(message):
    log_file = mypackage.config.log_file
    open(log_file, "a").write(message + "\n")

mypackage/config.py

import mypackage.logging

log_file = "/var/log/mypackage.log"

try:
    # Load some more config from file.
except Exception as e:
    # That's fine, just log that we couldn't open the file.
    mypackage.logging.log("Couldn't open config file: %s" % str(e))

问题是上面的代码存在循环依赖问题,在导入完成之前从mypackage/config.py调用mypackage.logging.log()意味着[=17]中的log_file = mypackage.config.log_file行=] 会失败。

是否可以将 mypackage/config.py 的静态部分导入到模块中,以便在调用 mypackage.logging.log() 时在 mypackage.config.log_file 可用?

如果做不到这一点,有没有更简洁的方法来设计这个而没有这个问题?

要使您当前的代码正常工作,您可以在 log 函数中导入 config.log_file

def log(message):
    from mypackage.config import log_file
    open(log_file, "a").write(message + "\n")

当然,你有很多重新设计整个系统的可能性。 例如,您可以将所有可以产生循环依赖的设置放入它们自己的配置文件中,然后从 logging.pyconfig.py.

中导入它