Python 如何让 PyLint 识别 numpy 成员?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20553551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:43:07  来源:igfitidea点击:

How do I get PyLint to recognize numpy members?

pythonnumpypylint

提问by Alphadelta14

I am running PyLint on a Python project. PyLint makes many complaints about being unable to find numpy members. How can I avoid this while avoiding skipping membership checks.

我在 Python 项目上运行 PyLint。PyLint 抱怨无法找到 numpy 成员。如何在避免跳过成员资格检查的同时避免这种情况。

From the code:

从代码:

import numpy as np

print np.zeros([1, 4])

Which, when ran, I get the expected:

其中,运行时,我得到了预期:

[[ 0. 0. 0. 0.]]

[[0.0.0.0.]]

However, pylint gives me this error:

但是,pylint 给了我这个错误:

E: 3, 6: Module 'numpy' has no 'zeros' member (no-member)

E: 3, 6: 模块 'numpy' 没有 'zeros' 成员(无成员)

For versions, I am using pylint 1.0.0 (astroid 1.0.1, common 0.60.0) and trying to work with numpy 1.8.0 .

对于版本,我使用 pylint 1.0.0(astroid 1.0.1,common 0.60.0)并尝试使用 numpy 1.8.0 。

回答by alko

Probably, it's confused with numpy's abstruse method of methods import. Namely, zerosis in fact numpy.core.multiarray.zeros, imported in numpy with statement

可能,它与 numpy 的方法导入的深奥方法混淆了。即,zeros实际上numpy.core.multiarray.zeros是在numpy中用语句导入

from .core import *

in turn imported with

依次导入

from .numeric import *

and in numeric you'll find

在数字中你会发现

zeros = multiarray.zeros

I guess I would be confused in place of PyLint!

我想我会因为 PyLint 而感到困惑!

See this bugfor PyLint side of view.

请参阅PyLint 侧视图的此错误

回答by flyingsolow

There have been many different bugs reported about this over the past few years i.e. https://bitbucket.org/logilab/pylint/issue/58/false-positive-no-member-on-numpy-imports

在过去的几年里,有很多关于这个的错误报告,即https://bitbucket.org/logilab/pylint/issue/58/false-positive-no-member-on-numpy-imports

I'd suggest disabling for the lines where the complaints occur.

我建议禁用发生投诉的线路。

# pylint: disable=E1103
print np.zeros([1, 4])
# pylint: enable=E1103

回答by dohmatob

I had this problem with numpy, scipy, sklearn, nipy, etc., and I solved it by wrapping epylint like so:

我在使用 numpy、scipy、sklearn、nipy 等时遇到了这个问题,我通过像这样包装 epylint 来解决它:

$ cat epylint.py

$猫epylint.py

#!/usr/bin/python

"""
Synopsis: epylint wrapper that filters a bunch of false-positive warnings and errors
Author: DOHMATOB Elvis Dopgima <[email protected]> <[email protected]>

"""

import os
import sys
import re
from subprocess import Popen, STDOUT, PIPE

NUMPY_HAS_NO_MEMBER = re.compile("Module 'numpy(?:\..+)?' has no '.+' member")
SCIPY_HAS_NO_MEMBER = re.compile("Module 'scipy(?:\..+)?' has no '.+' member")
SCIPY_HAS_NO_MEMBER2 = re.compile("No name '.+' in module 'scipy(?:\..+)?'")
NIPY_HAS_NO_MEMBER = re.compile("Module 'nipy(?:\..+)?' has no '.+' member")
SK_ATTR_DEFINED_OUTSIDE_INIT = re.compile("Attribute '.+_' defined outside __init__")
REL_IMPORT_SHOULD_BE = re.compile("Relative import '.+', should be '.+")
REDEFINING_NAME_FROM_OUTER_SCOPE = re.compile("Redefining name '.+' from outer scope")

if __name__ == "__main__":
    basename = os.path.basename(sys.argv[1])
    for line in Popen(['epylint', sys.argv[1], '--disable=C,R,I'  # filter thesew arnings
                       ], stdout=PIPE, stderr=STDOUT, universal_newlines=True).stdout:
        if line.startswith("***********"):
            continue
        elif line.startswith("No config file found,"):
            continue
        elif "anomalous-backslash-in-string," in line:
            continue
        if NUMPY_HAS_NO_MEMBER.search(line):
            continue
        if SCIPY_HAS_NO_MEMBER.search(line):
            continue
        if SCIPY_HAS_NO_MEMBER2.search(line):
            continue
        if "Used * or ** magic" in line:
            continue
        if "No module named" in line and "_flymake" in line:
            continue
        if SK_ATTR_DEFINED_OUTSIDE_INIT.search(line):
            continue
        if "Access to a protected member" in line:
            continue
        if REL_IMPORT_SHOULD_BE.search(line):
            continue
        if REDEFINING_NAME_FROM_OUTER_SCOPE.search(line):
            continue
        if NIPY_HAS_NO_MEMBER.search(line):
            continue
        # XXX extend by adding more handles for false-positives here
        else:
            print line,

This script simply runs epylint, then scrapes its output to filter out false-positive warnings and errors. You can extend it by added more elif cases.

该脚本简单地运行 epylint,然后抓取其输出以过滤掉误报警告和错误。您可以通过添加更多 elif 案例来扩展它。

N.B.: If this applies to you, then you'll want to modify your pychechers.sh so it likes like this

注意:如果这适用于你,那么你需要修改你的 pychechers.sh 让它像这样

#!/bin/bash

epylint.py "" 2>/dev/null
pyflakes ""
pep8 --ignore=E221,E701,E202 --repeat ""
true

(Of course, you have to make epylint.py executable first)

(当然,你必须先让 epylint.py 可执行)

Here is a link to my .emacs https://github.com/dohmatob/mydotemacs. Hope this is useful to someone.

这是我的 .emacs https://github.com/dohmatob/mydotemacs的链接。希望这对某人有用。

回答by jakebrinkmann

I had to add this at the top of any file where I use numpy a lot.

我必须在我经常使用 numpy 的任何文件的顶部添加它。

# To ignore numpy errors:
#     pylint: disable=E1101

Just in case someone in eclipse is having trouble with Pydev and pylint...

以防万一 eclipse 中的某个人在使用 Pydev 和 pylint 时遇到问题......

回答by Mateo

This is the pseudo-solution I have come up with for this problem.

这是我为这个问题提出的伪解决方案。

#pylint: disable=no-name-in-module
from numpy import array as np_array, transpose as np_transpose, \
      linspace as np_linspace, zeros as np_zeros
from numpy.random import uniform as random_uniform
#pylint: enable=no-name-in-module

Then, in your code, instead of calling numpyfunctions as np.arrayand np.zerosand so on, you would write np_array, np_zeros, etc. Advantages of this approach vs. other approaches suggested in other answers:

然后,在你的代码,而不是调用numpy功能np.arraynp.zeros等等,你会写np_arraynp_zeros等等。这种做法与在其他的答案提出其他方法的优点:

  • The pylint disable/enable is restricted to a small region of your code
  • That means that you don't have to surround every single line that has an invocation of a numpy function with a pylint directive.
  • You are not doing pylint disable of the error for your whole file, which might mask other issues with your code.
  • pylint 禁用/启用仅限于代码的一小部分
  • 这意味着您不必用 pylint 指令包围调用 numpy 函数的每一行。
  • 您没有对整个文件的错误进行 pylint 禁用,这可能会掩盖您的代码的其他问题。

The clear disadvantage is that you have to explicitely import every numpy function you use. The approach could be elaborated on further. You could define your own module, call it say, numpy_importeras follows

明显的缺点是您必须明确导入您使用的每个 numpy 函数。可以进一步详细说明该方法。你可以定义你自己的模块,叫它说,numpy_importer如下

""" module: numpy_importer.py
       explicitely import numpy functions while avoiding pylint errors  
"""
#pylint: disable=unused-import
#pylint: disable=no-name-in-module
from numpy import array, transpose, zeros  #add all things you need  
from numpy.random import uniform as random_uniform
#pylint: enable=no-name-in-module

Then, your application code could import this module only (instead of numpy) as

然后,您的应用程序代码只能导入此模块(而不是 numpy)作为

import numpy_importer as np 

and use the names as usual: np.zeros, np.arrayetc.

并且使用的名称像往常一样:np.zerosnp.array等等。

The advantage of this is that you will have a single module in which all numpyrelated imports are done once and for all, and then you import it with that single line, wherever you want. Still you have to be careful that numpy_importerdoes not import names that don′t exist in numpyas those errors won't be caught by pylint.

这样做的好处是您将拥有一个模块,其中所有numpy相关的导入都一劳永逸地完成,然后您可以在任何需要的地方使用该单行导入它。您仍然必须小心,numpy_importer不要导入不存在的名称,numpy因为 pylint 不会捕获这些错误。

回答by bijancn

Since this is the top result in google and it gave me the impression that you have to ignore those warnings in all files:

由于这是 google 中的最高结果,它给我的印象是您必须忽略所有文件中的这些警告:

The problem has actually been fixed in the sources of pylint/astroid last month https://bitbucket.org/logilab/astroid/commits/83d78af4866be5818f193360c78185e1008fd29ebut are not yet in the Ubuntu packages.

该问题实际上已在上个月的 pylint/astroid 源中得到解决https://bitbucket.org/logilab/astroid/commits/83d78af4866be5818f193360c78185e1008fd29e但尚未在 Ubuntu 软件包中。

To get the sources, just

要获取来源,只需

hg clone https://bitbucket.org/logilab/pylint/
hg clone https://bitbucket.org/logilab/astroid
mkdir logilab && touch logilab/__init__.py
hg clone http://hg.logilab.org/logilab/common logilab/common
cd pylint && python setup.py install

whereby the last step will most likely require a sudoand of course you need mercurial to clone.

其中最后一步很可能需要一个sudo,当然你需要 mercurial 来克隆。

回答by Czarek Tomczak

I've been working on a patch to pylint to solve the issue with dynamic members in libraries such as numpy. It adds a "dynamic-modules" option which forces to check if members exist during runtime by making a real import of the module. See Issue #413 in logilab/pylint. There is also a pull request, see link in one of the comments.

我一直在研究 pylint 的补丁,以解决库中动态成员的问题,例如 numpy。它添加了一个“动态模块”选项,通过真正导入模块来强制检查成员在运行时是否存在。请参阅logilab/pylint 中的问题 #413。还有一个拉取请求,请参阅其中一条评论中的链接。

回答by paduwan

I had the same issue here, even with the latest versions of all related packages (astroid 1.3.2, logilab_common 0.63.2, pylon 1.4.0).

我在这里遇到了同样的问题,即使是所有相关包的最新版本 ( astroid 1.3.2, logilab_common 0.63.2, pylon 1.4.0)。

The following solution worked like a charm: I added numpyto the list of ignored modules by modifying my pylintrcfile, in the [TYPECHECK]section:

以下解决方案就像一个魅力:我numpy通过修改我的pylintrc文件,在[TYPECHECK]部分中添加到被忽略模块的列表中:

[TYPECHECK]

ignored-modules = numpy

Depending on the error, you might also need to add the following line (still in the [TYPECHECK] section):

根据错误,您可能还需要添加以下行(仍在 中[TYPECHECK] section):

ignored-classes = numpy

回答by j_houg

In recent versions of pylint you can add --extension-pkg-whitelist=numpyto your pylint command. They had fixed this problem in an earlier version in an unsafe way. Now if you want them to look more carefully at a package outside of the standard library, you must explicitly whitelist it. See here.

在最新版本的 pylint 中,您可以添加--extension-pkg-whitelist=numpy到 pylint 命令中。他们在早期版本中以不安全的方式修复了这个问题。现在,如果您希望他们更仔细地查看标准库之外的包,则必须明确将其列入白名单。看这里。

回答by Tomi Aarnio

This seems to work on at least Pylint 1.1.0:

这似乎至少适用于 Pylint 1.1.0:

[TYPECHECK]

ignored-classes=numpy