python - 皮林特 - "Using the global statement"

标签 python global-variables warnings pylint

我正在努力处理我当前的 python 程序,非常注意 pylint 警告,所以虽然我意识到我可以简单地关闭警告,但我想确保在我这样做之前没有更理想的解决方案。

我当前的代码部分是我的日志记录代码。我有一个函数 init() 可以设置处理程序并将它们附加到根记录器,还有一个函数 set_console_level(level) 可以设置报告控制台消息的级别(调试、信息等):

_CONSOLE_OUT = NONE

def init():
    """Set up the error handlers for the root logger"""
    console_out = logging.StreamHandler()
    console_out.setLevel(logging.INFO)  #Show info messages for now
    #...
    logging.root.addHandler(console_out)
    global _CONSOLE_OUT
    _CONSOLE_OUT = console_out

    #Rest of function sets up more handlers similarly
init()

def set_console_level(level):
    """Change the level at which console messages are printed"""
    assert __CONSOLE_OUT is not None #Set in init
    _CONSOLE_OUT.setLevel(level) 

据我所知,这是执行此操作的方法。需要行 global _CONSOLE_OUT 才能写入模块级变量。但是,当我在此文件上运行 pylint 时,我收到警告 W: 15,4:init: Using the global statement。有没有办法避免这个警告?解决这个问题的更好方法?

(请不要在没有给出理由的情况下说global _CONSOLE_OUT #pylint: disable=W****)

最佳答案

您可以在导入时创建它:

_console_out = ConsoleHandler()

其中 ConsoleHandler 是一个工厂函数或您的创建和设置处理程序的类。

关于python - 皮林特 - "Using the global statement",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12152971/

相关文章:

r - 如何处理 K-means 函数中的 "empty cluster"警告?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

python - Django is_valid() 不适用于 modelformset_factory

python - 在线程之间共享对象时如何避免 pickle 错误?

python - 我应该用 Python 命名我的全局模块?

ios - 使用在另一个 Swift VC 文件中创建的对象?

php - 提供的参数不是有效的 MySQL 结果

python - 如何从网站下载文件

Python 正则表达式与换行符匹配

python - 为什么在这种情况下不需要 global 关键字?