“未使用的导入警告"和皮林特 [英] "Unused import warning" and pylint

查看:53
本文介绍了“未使用的导入警告"和皮林特的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在用 Python 开发一个项目,并试图用 pylint 和一般的 .所以,我有一个源文件,(我们就叫它 a.py)

So I'm working on a project in Python and trying to keep it up to standards with pylint and just generally . So, I have a source file, (We'll just call it a.py)

#a.py
import loggingsetup

def foo():
   log.info("This is a log message")

但是,我想控制日志的样子,所以在 loggingsetup 中我有类似的东西:

But, I want to control what the logging looks like, so in loggingsetup I have something like:

#loggingsetup.py
import logging

logging.root.setLevel(logging.DEBUG)

consoleOut = logging.StreamHandler()
consoleOut.setLevel(logging.INFO)  
consoleOut.setFormatter(logging.Formatter("\t"+logging.BASIC_FORMAT))
logging.root.addHandler(consoleOut)

#etc

现在,这似乎没问题.我想作为一个初步问题,我应该问这是否是解决此问题的正确方法,或者是否有其他更好的方式来构建我的代码.

Now, this seems to work alright. I suppose as a preliminary question I should ask if this is the right way to go about this, or if there's a different way of structuring my code that would be preferable.

但我的主要问题是,当我在 a.py 上运行 pylint 时,会收到类似未使用的导入 - 导入 loggingsetup"的警告,因为我实际上并没有从 loggingsetup 调用任何方法或函数.

But my main question is that when I run pylint on a.py I get a warning like "unused import - import loggingsetup", since I'm not actually calling any methods or functions from loggingsetup.

我可以做一些事情,例如将 loggingsetup 的主体重新定义为函数并调用它,但它看起来很愚蠢且容易出错(如果我确实从其他地方导入 loggingsetup,我将不得不担心调用它两次,如果我了解 python 如何处理导入,这不是我当前设置的问题).

I could do something like redefine the body of loggingsetup as a function and call it, but it seems silly and error-prone (I'd have to worry about calling it twice if I did import loggingsetup from somewhere else, and if I understand how python handles imports, that's not an issue with my current setup).

我显然可以告诉 pylint 忽略警告,但我想我会先在这里询问以确保这实际上不是我应该以不同方式处理的事情.

I could obviously just tell pylint to ignore the warning, but I thought I'd ask here first to make sure that this isn't actually something that I should handle differently.

推荐答案

我将使用的方法是使用 loggingsetup 作为 logging 的一种包装器.

The approach I would use is to use loggingsetup as a sort of wrapper for logging.

import logging

# set up logging config here

from logging import *

然后在您的其他模块中:

Then in your other modules you:

import loggingsetup as logging

在这种情况下,您可能想要使用 loggingsetup 以外的名称,例如tweaked_logginglogging_with_my_settings.

You might want to use a name other than loggingsetup in this case, e.g. tweaked_logging or logging_with_my_settings.

这篇关于“未使用的导入警告"和皮林特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆