从Python中导入的模块的__init__.py中记录消息

huangapple go评论65阅读模式
英文:

Logging messages from __init__.py of an imported module in Python

问题

我编写了一些库,部分代码依赖于环境变量。

因此,这些库的__init__.py文件包含一些逻辑,用于解析环境文件或设置默认值。

由于这些环境变量会影响代码,我在__init__.py中设置了一个记录器,并记录是否找到了环境文件等信息。

如果我现在编写一个脚本并希望配置记录器,如果在导入之前不配置记录器,我会错过这些消息。另一方面,导入应该首先进行。

有没有更好的解决方法来处理这个问题?

英文:

I wrote some libraries and part of the code relies on environment variables.

Therefor the init.py files of those libraries have some logic to parse env files or set defaults.

Since this envvars influence the code, I set up a logger in init.py and I am logging whether an env file was found etc.

If I am now writing a skript and want to configure a logger, I am missing those messages if I don't configure the logger before the import. On the other hand imports should come first.

What is a better way to solve this topic?

答案1

得分: 1

以下是您要翻译的内容:

  1. 打破“首先导入”的规则--这不是闻所未闻的,因为有时候有很好的理由这样做,但在你的情况下,我认为这有点像是一个hack。你可能应该这样做:

  2. 不要在顶层读取环境文件/变量,这在模块导入时执行。

听起来你正在做类似这样的事情:

# foo.py
import os

CONFIG = os.getenv('SOMETHING')  # 这在模块被导入时运行,即文件被加载
# main.py
import foo  # 正在这里导入

# 做一些事情,但是foo.py中的顶层代码已经执行了

相反:

# foo.py
import os
import functools as ft

@ft.cache
def config():
    return os.getenv('SOMETHING')  # 在函数内部,而不是在顶层
# main.py
import foo

# 此时,foo.config()已被定义,但尚未执行

configure_logger()

foo.config()
foo.config()  # 返回值被缓存,因此不会重新执行,返回相同的值

# 做一些事情
英文:

Couple options:

  1. Break the "imports come first" rule -- it's not unheard of b/c there are sometimes good reasons to do this, but I'd consider it a bit of a hack in your case, i.e. what you should probably do is:

  2. Don't read the env files/vars at the top level, which executes on module import.

It sounds like you're doing something like:

# foo.py
import os

CONFIG = os.getenv('SOMETHING')  # this runs module is imported, i.e. the file is loaded
# main.py
import foo  # right here

# do stuff, but toplevel code in foo.py has already executed

Instead:

# foo.py
import os
import functools as ft

@ft.cache
def config():
    return os.getenv('SOMETHING')  # inside a function, not top-level
# main.py
import foo

# at this point, foo.config() has been defined, but not executed

configure_logger()

foo.config()
foo.config()  # return value is cached, so same value is returned without re-executing

# do stuff

huangapple
  • 本文由 发表于 2023年5月11日 13:19:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224352.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定