The following issues were found
numpy/typing/tests/data/pass/index_tricks.py
15 issues
Line: 10
Column: 8
AR_LIKE_f = [[1.0, 2.0], [3.0, 4.0]]
AR_LIKE_U = [["1", "2"], ["3", "4"]]
AR_i8: np.ndarray[Any, np.dtype[np.int64]] = np.array(AR_LIKE_i, dtype=np.int64)
np.ndenumerate(AR_i8)
np.ndenumerate(AR_LIKE_f)
np.ndenumerate(AR_LIKE_U)
Reported by Pylint.
Line: 16
Column: 1
np.ndenumerate(AR_LIKE_f)
np.ndenumerate(AR_LIKE_U)
np.ndenumerate(AR_i8).iter
np.ndenumerate(AR_LIKE_f).iter
np.ndenumerate(AR_LIKE_U).iter
next(np.ndenumerate(AR_i8))
next(np.ndenumerate(AR_LIKE_f))
Reported by Pylint.
Line: 17
Column: 1
np.ndenumerate(AR_LIKE_U)
np.ndenumerate(AR_i8).iter
np.ndenumerate(AR_LIKE_f).iter
np.ndenumerate(AR_LIKE_U).iter
next(np.ndenumerate(AR_i8))
next(np.ndenumerate(AR_LIKE_f))
next(np.ndenumerate(AR_LIKE_U))
Reported by Pylint.
Line: 18
Column: 1
np.ndenumerate(AR_i8).iter
np.ndenumerate(AR_LIKE_f).iter
np.ndenumerate(AR_LIKE_U).iter
next(np.ndenumerate(AR_i8))
next(np.ndenumerate(AR_LIKE_f))
next(np.ndenumerate(AR_LIKE_U))
Reported by Pylint.
Line: 41
Column: 1
np.ravel_multi_index(AR_LIKE_i, (4, 4), mode=('clip', 'wrap'))
np.ravel_multi_index((3, 1, 4, 1), (6, 7, 8, 9))
np.mgrid[1:1:2]
np.mgrid[1:1:2, None:10]
np.ogrid[1:1:2]
np.ogrid[1:1:2, None:10]
Reported by Pylint.
Line: 42
Column: 1
np.ravel_multi_index((3, 1, 4, 1), (6, 7, 8, 9))
np.mgrid[1:1:2]
np.mgrid[1:1:2, None:10]
np.ogrid[1:1:2]
np.ogrid[1:1:2, None:10]
np.index_exp[0:1]
Reported by Pylint.
Line: 44
Column: 1
np.mgrid[1:1:2]
np.mgrid[1:1:2, None:10]
np.ogrid[1:1:2]
np.ogrid[1:1:2, None:10]
np.index_exp[0:1]
np.index_exp[0:1, None:3]
np.index_exp[0, 0:1, ..., [0, 1, 3]]
Reported by Pylint.
Line: 45
Column: 1
np.mgrid[1:1:2, None:10]
np.ogrid[1:1:2]
np.ogrid[1:1:2, None:10]
np.index_exp[0:1]
np.index_exp[0:1, None:3]
np.index_exp[0, 0:1, ..., [0, 1, 3]]
Reported by Pylint.
Line: 47
Column: 1
np.ogrid[1:1:2]
np.ogrid[1:1:2, None:10]
np.index_exp[0:1]
np.index_exp[0:1, None:3]
np.index_exp[0, 0:1, ..., [0, 1, 3]]
np.s_[0:1]
np.s_[0:1, None:3]
Reported by Pylint.
Line: 48
Column: 1
np.ogrid[1:1:2, None:10]
np.index_exp[0:1]
np.index_exp[0:1, None:3]
np.index_exp[0, 0:1, ..., [0, 1, 3]]
np.s_[0:1]
np.s_[0:1, None:3]
np.s_[0, 0:1, ..., [0, 1, 3]]
Reported by Pylint.
numpy/core/_exceptions.py
15 issues
Line: 34
Column: 5
class UFuncTypeError(TypeError):
""" Base class for all ufunc exceptions """
def __init__(self, ufunc):
self.ufunc = ufunc
@_display_as_base
class _UFuncBinaryResolutionError(UFuncTypeError):
Reported by Pylint.
Line: 191
Column: 5
__slots__ = ("axis", "ndim", "_msg")
def __init__(self, axis, ndim=None, msg_prefix=None):
if ndim is msg_prefix is None:
# single-argument form: directly set the error message
self._msg = axis
self.axis = None
self.ndim = None
Reported by Pylint.
Line: 191
Column: 5
__slots__ = ("axis", "ndim", "_msg")
def __init__(self, axis, ndim=None, msg_prefix=None):
if ndim is msg_prefix is None:
# single-argument form: directly set the error message
self._msg = axis
self.axis = None
self.ndim = None
Reported by Pylint.
Line: 218
Column: 5
@_display_as_base
class _ArrayMemoryError(MemoryError):
""" Thrown when an array cannot be allocated"""
def __init__(self, shape, dtype):
self.shape = shape
self.dtype = dtype
@property
def _total_size(self):
Reported by Pylint.
Line: 11
Column: 5
from numpy.core.overrides import set_module
def _unpack_tuple(tup):
if len(tup) == 1:
return tup[0]
else:
return tup
Reported by Pylint.
Line: 27
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
Classes decorated with this decorator are subject to removal without a
deprecation warning.
"""
assert issubclass(cls, Exception)
cls.__name__ = cls.__base__.__name__
return cls
class UFuncTypeError(TypeError):
Reported by Bandit.
Line: 44
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
def __init__(self, ufunc, dtypes):
super().__init__(ufunc)
self.dtypes = tuple(dtypes)
assert len(self.dtypes) == 2
def __str__(self):
return (
"ufunc {!r} cannot use operands with types {!r} and {!r}"
).format(
Reported by Bandit.
Line: 78
Column: 9
super().__init__(ufunc)
self.casting = casting
self.from_ = from_
self.to = to
@_display_as_base
class _UFuncInputCastingError(_UFuncCastingError):
""" Thrown when a ufunc input cannot be casted """
Reported by Pylint.
Line: 84
Column: 5
@_display_as_base
class _UFuncInputCastingError(_UFuncCastingError):
""" Thrown when a ufunc input cannot be casted """
def __init__(self, ufunc, casting, from_, to, i):
super().__init__(ufunc, casting, from_, to)
self.in_i = i
def __str__(self):
# only show the number if more than one input exists
Reported by Pylint.
Line: 102
Column: 5
@_display_as_base
class _UFuncOutputCastingError(_UFuncCastingError):
""" Thrown when a ufunc output cannot be casted """
def __init__(self, ufunc, casting, from_, to, i):
super().__init__(ufunc, casting, from_, to)
self.out_i = i
def __str__(self):
# only show the number if more than one output exists
Reported by Pylint.
numpy/typing/tests/data/pass/numerictypes.py
15 issues
Line: 31
Column: 1
np.find_common_type([np.int64, np.float32], [])
np.find_common_type([np.float32], [np.int64, np.float64])
np.cast[int]
np.cast["i8"]
np.cast[np.int64]
np.nbytes[int]
np.nbytes["i8"]
Reported by Pylint.
Line: 32
Column: 1
np.find_common_type([np.float32], [np.int64, np.float64])
np.cast[int]
np.cast["i8"]
np.cast[np.int64]
np.nbytes[int]
np.nbytes["i8"]
np.nbytes[np.int64]
Reported by Pylint.
Line: 33
Column: 1
np.cast[int]
np.cast["i8"]
np.cast[np.int64]
np.nbytes[int]
np.nbytes["i8"]
np.nbytes[np.int64]
Reported by Pylint.
Line: 35
Column: 1
np.cast["i8"]
np.cast[np.int64]
np.nbytes[int]
np.nbytes["i8"]
np.nbytes[np.int64]
np.ScalarType
np.ScalarType[0]
Reported by Pylint.
Line: 36
Column: 1
np.cast[np.int64]
np.nbytes[int]
np.nbytes["i8"]
np.nbytes[np.int64]
np.ScalarType
np.ScalarType[0]
np.ScalarType[4]
Reported by Pylint.
Line: 37
Column: 1
np.nbytes[int]
np.nbytes["i8"]
np.nbytes[np.int64]
np.ScalarType
np.ScalarType[0]
np.ScalarType[4]
np.ScalarType[9]
Reported by Pylint.
Line: 39
Column: 1
np.nbytes["i8"]
np.nbytes[np.int64]
np.ScalarType
np.ScalarType[0]
np.ScalarType[4]
np.ScalarType[9]
np.ScalarType[11]
Reported by Pylint.
Line: 40
Column: 1
np.nbytes[np.int64]
np.ScalarType
np.ScalarType[0]
np.ScalarType[4]
np.ScalarType[9]
np.ScalarType[11]
np.typecodes["Character"]
Reported by Pylint.
Line: 41
Column: 1
np.ScalarType
np.ScalarType[0]
np.ScalarType[4]
np.ScalarType[9]
np.ScalarType[11]
np.typecodes["Character"]
np.typecodes["Complex"]
Reported by Pylint.
Line: 42
Column: 1
np.ScalarType
np.ScalarType[0]
np.ScalarType[4]
np.ScalarType[9]
np.ScalarType[11]
np.typecodes["Character"]
np.typecodes["Complex"]
np.typecodes["All"]
Reported by Pylint.
numpy/conftest.py
15 issues
Line: 7
Column: 1
import os
import tempfile
import hypothesis
import pytest
import numpy
from numpy.core._multiarray_tests import get_fpu_mode
Reported by Pylint.
Line: 8
Column: 1
import tempfile
import hypothesis
import pytest
import numpy
from numpy.core._multiarray_tests import get_fpu_mode
Reported by Pylint.
Line: 11
Column: 1
import pytest
import numpy
from numpy.core._multiarray_tests import get_fpu_mode
_old_fpu_mode = None
_collect_results = {}
Reported by Pylint.
Line: 71
Column: 2
os.environ['NPY_AVAILABLE_MEM'] = available_mem
#FIXME when yield tests are gone.
@pytest.hookimpl()
def pytest_itemcollected(item):
"""
Check FPU precision mode was not changed during test collection.
Reported by Pylint.
Line: 81
Column: 5
still uses yield tests, which can execute code at test collection
time.
"""
global _old_fpu_mode
mode = get_fpu_mode()
if _old_fpu_mode is None:
_old_fpu_mode = mode
Reported by Pylint.
Line: 14
Column: 1
from numpy.core._multiarray_tests import get_fpu_mode
_old_fpu_mode = None
_collect_results = {}
# Use a known and persistent tmpdir for hypothesis' caches, which
# can be automatically cleared by the OS or user.
hypothesis.configuration.set_hypothesis_home_dir(
Reported by Pylint.
Line: 25
Column: 61
# We register two custom profiles for Numpy - for details see
# https://hypothesis.readthedocs.io/en/latest/settings.html
# The first is designed for our own CI runs; the latter also
# forces determinism and is designed for use via np.test()
hypothesis.settings.register_profile(
name="numpy-profile", deadline=None, print_blob=True,
)
hypothesis.settings.register_profile(
Reported by Pylint.
Line: 35
Column: 64
deadline=None, print_blob=True, database=None, derandomize=True,
suppress_health_check=hypothesis.HealthCheck.all(),
)
# Note that the default profile is chosen based on the presence
# of pytest.ini, but can be overriden by passing the
# --hypothesis-profile=NAME argument to pytest.
_pytest_ini = os.path.join(os.path.dirname(__file__), "..", "pytest.ini")
hypothesis.settings.load_profile(
"numpy-profile" if os.path.isfile(_pytest_ini) else "np.test() profile"
Reported by Pylint.
Line: 36
Column: 53
suppress_health_check=hypothesis.HealthCheck.all(),
)
# Note that the default profile is chosen based on the presence
# of pytest.ini, but can be overriden by passing the
# --hypothesis-profile=NAME argument to pytest.
_pytest_ini = os.path.join(os.path.dirname(__file__), "..", "pytest.ini")
hypothesis.settings.load_profile(
"numpy-profile" if os.path.isfile(_pytest_ini) else "np.test() profile"
)
Reported by Pylint.
Line: 44
Column: 1
)
def pytest_configure(config):
config.addinivalue_line("markers",
"valgrind_error: Tests that are known to error under valgrind.")
config.addinivalue_line("markers",
"leaks_references: Tests that are known to leak references.")
config.addinivalue_line("markers",
Reported by Pylint.
numpy/compat/_inspect.py
15 issues
Line: 13
Column: 14
__all__ = ['getargspec', 'formatargspec']
# ----------------------------------------------------------- type-checking
def ismethod(object):
"""Return true if the object is an instance method.
Instance method objects provide these attributes:
__doc__ documentation string
__name__ name with which this method was defined
Reported by Pylint.
Line: 26
Column: 16
"""
return isinstance(object, types.MethodType)
def isfunction(object):
"""Return true if the object is a user-defined function.
Function objects provide these attributes:
__doc__ documentation string
__name__ name with which this function was defined
Reported by Pylint.
Line: 41
Column: 12
"""
return isinstance(object, types.FunctionType)
def iscode(object):
"""Return true if the object is a code object.
Code objects provide these attributes:
co_argcount number of arguments (not including * or ** args)
co_code string of raw compiled bytecode
Reported by Pylint.
Line: 131
Column: 12
else:
return '(' + ', '.join(seq) + ')'
def strseq(object, convert, join=joinseq):
"""Recursively walk a sequence, stringifying each element.
"""
if type(object) in [list, tuple]:
return join([strseq(_o, convert, join) for _o in object])
Reported by Pylint.
Line: 168
Column: 43
specs.append(formatvarkw(varkw))
return '(' + ', '.join(specs) + ')'
def formatargvalues(args, varargs, varkw, locals,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value),
join=joinseq):
Reported by Pylint.
Line: 182
Column: 23
argument is an optional function to format the sequence of arguments.
"""
def convert(name, locals=locals,
formatarg=formatarg, formatvalue=formatvalue):
return formatarg(name) + formatvalue(locals[name])
specs = [strseq(arg, convert, join) for arg in args]
if varargs:
Reported by Pylint.
Line: 57
Column: 1
co_nlocals number of local variables
co_stacksize virtual machine stack space required
co_varnames tuple of names of arguments and local variables
"""
return isinstance(object, types.CodeType)
# ------------------------------------------------ argument list extraction
# These constants are from Python's compile.h.
Reported by Pylint.
Line: 65
Column: 1
# These constants are from Python's compile.h.
CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8
def getargs(co):
"""Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where 'args' is
a list of argument names (possibly containing nested lists), and
'varargs' and 'varkw' are the names of the * and ** arguments or None.
Reported by Pylint.
Line: 120
Column: 1
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'locals' is the locals dictionary of the given frame.
"""
args, varargs, varkw = getargs(frame.f_code)
return args, varargs, varkw, frame.f_locals
def joinseq(seq):
Reported by Pylint.
Line: 125
Column: 1
args, varargs, varkw = getargs(frame.f_code)
return args, varargs, varkw, frame.f_locals
def joinseq(seq):
if len(seq) == 1:
return '(' + seq[0] + ',)'
else:
return '(' + ', '.join(seq) + ')'
Reported by Pylint.
numpy/distutils/fcompiler/environment.py
15 issues
Line: 15
Column: 41
def dump_variable(self, name):
conf_desc = self._conf_keys[name]
hook, envvar, confvar, convert, append = conf_desc
if not convert:
convert = lambda x : x
print('%s.%s:' % (self._distutils_section, name))
v = self._hook_handler(name, hook)
print(' hook : %s' % (convert(v),))
Reported by Pylint.
Line: 73
Column: 17
var = envvar_contents
if confvar is not None and self._conf:
if confvar in self._conf:
source, confvar_contents = self._conf[confvar]
var = convert(confvar_contents)
return var
def clone(self, hook_handler):
Reported by Pylint.
Line: 81
Column: 9
def clone(self, hook_handler):
ec = self.__class__(distutils_section=self._distutils_section,
**self._conf_keys)
ec._hook_handler = hook_handler
return ec
def use_distribution(self, dist):
if isinstance(dist, Distribution):
self._conf = dist.get_option_dict(self._distutils_section)
Reported by Pylint.
Line: 1
Column: 1
import os
from distutils.dist import Distribution
__metaclass__ = type
class EnvironmentConfig:
def __init__(self, distutils_section='ALL', **kw):
self._distutils_section = distutils_section
self._conf_keys = kw
Reported by Pylint.
Line: 4
Column: 1
import os
from distutils.dist import Distribution
__metaclass__ = type
class EnvironmentConfig:
def __init__(self, distutils_section='ALL', **kw):
self._distutils_section = distutils_section
self._conf_keys = kw
Reported by Pylint.
Line: 6
Column: 1
__metaclass__ = type
class EnvironmentConfig:
def __init__(self, distutils_section='ALL', **kw):
self._distutils_section = distutils_section
self._conf_keys = kw
self._conf = None
self._hook_handler = None
Reported by Pylint.
Line: 13
Column: 5
self._conf = None
self._hook_handler = None
def dump_variable(self, name):
conf_desc = self._conf_keys[name]
hook, envvar, confvar, convert, append = conf_desc
if not convert:
convert = lambda x : x
print('%s.%s:' % (self._distutils_section, name))
Reported by Pylint.
Line: 19
Column: 9
if not convert:
convert = lambda x : x
print('%s.%s:' % (self._distutils_section, name))
v = self._hook_handler(name, hook)
print(' hook : %s' % (convert(v),))
if envvar:
v = os.environ.get(envvar, None)
print(' environ: %s' % (convert(v),))
if confvar and self._conf:
Reported by Pylint.
Line: 22
Column: 13
v = self._hook_handler(name, hook)
print(' hook : %s' % (convert(v),))
if envvar:
v = os.environ.get(envvar, None)
print(' environ: %s' % (convert(v),))
if confvar and self._conf:
v = self._conf.get(confvar, (None, None))[1]
print(' config : %s' % (convert(v),))
Reported by Pylint.
Line: 25
Column: 13
v = os.environ.get(envvar, None)
print(' environ: %s' % (convert(v),))
if confvar and self._conf:
v = self._conf.get(confvar, (None, None))[1]
print(' config : %s' % (convert(v),))
def dump_variables(self):
for name in self._conf_keys:
self.dump_variable(name)
Reported by Pylint.
numpy/random/setup.py
15 issues
Line: 16
Column: 33
from numpy.distutils.misc_util import Configuration, get_mathlibs
config = Configuration('random', parent_package, top_path)
def generate_libraries(ext, build_dir):
config_cmd = config.get_config_cmd()
libs = get_mathlibs()
if sys.platform == 'win32':
libs.extend(['Advapi32', 'Kernel32'])
ext.libraries.extend(libs)
Reported by Pylint.
Line: 16
Column: 5
from numpy.distutils.misc_util import Configuration, get_mathlibs
config = Configuration('random', parent_package, top_path)
def generate_libraries(ext, build_dir):
config_cmd = config.get_config_cmd()
libs = get_mathlibs()
if sys.platform == 'win32':
libs.extend(['Advapi32', 'Kernel32'])
ext.libraries.extend(libs)
Reported by Pylint.
Line: 17
Column: 9
config = Configuration('random', parent_package, top_path)
def generate_libraries(ext, build_dir):
config_cmd = config.get_config_cmd()
libs = get_mathlibs()
if sys.platform == 'win32':
libs.extend(['Advapi32', 'Kernel32'])
ext.libraries.extend(libs)
return None
Reported by Pylint.
Line: 1
Column: 1
import os
import platform
import sys
from os.path import join
from numpy.distutils.system_info import platform_bits
is_msvc = (platform.platform().startswith('Windows') and
platform.python_compiler().startswith('MS'))
Reported by Pylint.
Line: 12
Column: 1
platform.python_compiler().startswith('MS'))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_mathlibs
config = Configuration('random', parent_package, top_path)
def generate_libraries(ext, build_dir):
config_cmd = config.get_config_cmd()
Reported by Pylint.
Line: 12
Column: 1
platform.python_compiler().startswith('MS'))
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_mathlibs
config = Configuration('random', parent_package, top_path)
def generate_libraries(ext, build_dir):
config_cmd = config.get_config_cmd()
Reported by Pylint.
Line: 13
Column: 5
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration, get_mathlibs
config = Configuration('random', parent_package, top_path)
def generate_libraries(ext, build_dir):
config_cmd = config.get_config_cmd()
libs = get_mathlibs()
Reported by Pylint.
Line: 16
Column: 5
from numpy.distutils.misc_util import Configuration, get_mathlibs
config = Configuration('random', parent_package, top_path)
def generate_libraries(ext, build_dir):
config_cmd = config.get_config_cmd()
libs = get_mathlibs()
if sys.platform == 'win32':
libs.extend(['Advapi32', 'Kernel32'])
ext.libraries.extend(libs)
Reported by Pylint.
Line: 38
Column: 5
config.add_data_dir('tests/data')
config.add_data_dir('_examples')
EXTRA_LINK_ARGS = []
EXTRA_LIBRARIES = ['npyrandom']
if os.name != 'nt':
# Math lib
EXTRA_LIBRARIES.append('m')
# Some bit generators exclude GCC inlining
Reported by Pylint.
Line: 39
Column: 5
config.add_data_dir('_examples')
EXTRA_LINK_ARGS = []
EXTRA_LIBRARIES = ['npyrandom']
if os.name != 'nt':
# Math lib
EXTRA_LIBRARIES.append('m')
# Some bit generators exclude GCC inlining
EXTRA_COMPILE_ARGS = ['-U__GNUC_GNU_INLINE__']
Reported by Pylint.
numpy/core/src/umath/ufunc_object.c
15 issues
Line: 63
Column: 35
CWE codes:
134
Suggestion:
Use a constant for the format specification
#if NPY_UF_DBG_TRACING
#define NPY_UF_DBG_PRINT(s) {printf("%s", s);fflush(stdout);}
#define NPY_UF_DBG_PRINT1(s, p1) {printf((s), (p1));fflush(stdout);}
#define NPY_UF_DBG_PRINT2(s, p1, p2) {printf(s, p1, p2);fflush(stdout);}
#define NPY_UF_DBG_PRINT3(s, p1, p2, p3) {printf(s, p1, p2, p3);fflush(stdout);}
#else
#define NPY_UF_DBG_PRINT(s)
#define NPY_UF_DBG_PRINT1(s, p1)
Reported by FlawFinder.
Line: 64
Column: 39
CWE codes:
134
Suggestion:
Use a constant for the format specification
#if NPY_UF_DBG_TRACING
#define NPY_UF_DBG_PRINT(s) {printf("%s", s);fflush(stdout);}
#define NPY_UF_DBG_PRINT1(s, p1) {printf((s), (p1));fflush(stdout);}
#define NPY_UF_DBG_PRINT2(s, p1, p2) {printf(s, p1, p2);fflush(stdout);}
#define NPY_UF_DBG_PRINT3(s, p1, p2, p3) {printf(s, p1, p2, p3);fflush(stdout);}
#else
#define NPY_UF_DBG_PRINT(s)
#define NPY_UF_DBG_PRINT1(s, p1)
#define NPY_UF_DBG_PRINT2(s, p1, p2)
Reported by FlawFinder.
Line: 65
Column: 43
CWE codes:
134
Suggestion:
Use a constant for the format specification
#define NPY_UF_DBG_PRINT(s) {printf("%s", s);fflush(stdout);}
#define NPY_UF_DBG_PRINT1(s, p1) {printf((s), (p1));fflush(stdout);}
#define NPY_UF_DBG_PRINT2(s, p1, p2) {printf(s, p1, p2);fflush(stdout);}
#define NPY_UF_DBG_PRINT3(s, p1, p2, p3) {printf(s, p1, p2, p3);fflush(stdout);}
#else
#define NPY_UF_DBG_PRINT(s)
#define NPY_UF_DBG_PRINT1(s, p1)
#define NPY_UF_DBG_PRINT2(s, p1, p2)
#define NPY_UF_DBG_PRINT3(s, p1, p2, p3)
Reported by FlawFinder.
Line: 640
Column: 9
CWE codes:
120
Suggestion:
Consider using snprintf, strcpy_s, or strlcpy (warning: strncpy easily misused)
len = strlen(signature);
ufunc->core_signature = PyArray_malloc(sizeof(char) * (len+1));
if (ufunc->core_signature) {
strcpy(ufunc->core_signature, signature);
}
/* Allocate sufficient memory to store pointers to all dimension names */
var_names = PyArray_malloc(sizeof(char const*) * len);
if (var_names == NULL) {
PyErr_NoMemory();
Reported by FlawFinder.
Line: 1299
Column: 5
CWE codes:
119
120
Suggestion:
Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length
* We can use the trivial (single inner-loop call) optimization
* and `fixed_strides` holds the strides for that call.
*/
char *data[NPY_MAXARGS];
npy_intp count = PyArray_MultiplyList(operation_shape, operation_ndim);
NPY_BEGIN_THREADS_DEF;
PyArrayMethod_StridedLoop *strided_loop;
NpyAuxData *auxdata = NULL;
Reported by FlawFinder.
Line: 1455
Column: 5
CWE codes:
119
120
Suggestion:
Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length
/* Call the __array_prepare__ functions for newly allocated arrays */
PyArrayObject **op_it = NpyIter_GetOperandArray(iter);
char *baseptrs[NPY_MAXARGS];
for (int i = 0; i < nout; ++i) {
if (op[nin + i] == NULL) {
op[nin + i] = op_it[nin + i];
Py_INCREF(op[nin + i]);
Reported by FlawFinder.
Line: 2458
Column: 5
CWE codes:
120
Suggestion:
Make sure destination can always hold the source data
* done in the inner-loop itself (not the iterator).
*/
assert(!NpyIter_IsBuffered(iter));
memcpy(inner_strides, NpyIter_GetInnerStrideArray(iter),
NPY_SIZEOF_INTP * nop);
/* Final preparation of the arraymethod call */
PyArrayMethod_Context context = {
.caller = (PyObject *)ufunc,
Reported by FlawFinder.
Line: 2817
Column: 5
CWE codes:
119
120
Suggestion:
Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length
{
PyArray_Descr *dtypes[3], **iter_dtypes;
PyUFuncObject *ufunc = (PyUFuncObject *)data;
char *dataptrs_copy[3];
npy_intp strides_copy[3];
npy_bool masked;
/* The normal selected inner loop */
PyUFuncGenericFunction innerloop = NULL;
Reported by FlawFinder.
Line: 3220
Column: 9
CWE codes:
119
120
Suggestion:
Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length
}
if (iter && NpyIter_GetIterSize(iter) != 0) {
char *dataptr_copy[3];
npy_intp stride_copy[3];
npy_intp count_m1, stride0, stride1;
NpyIter_IterNextFunc *iternext;
char **dataptr;
Reported by FlawFinder.
Line: 3291
Column: 9
CWE codes:
119
120
Suggestion:
Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length
NPY_END_THREADS;
}
else if (iter == NULL) {
char *dataptr_copy[3];
npy_intp stride_copy[3];
int itemsize = op_dtypes[0]->elsize;
/* Execute the loop with no iterators */
Reported by FlawFinder.
benchmarks/benchmarks/bench_import.py
14 issues
Line: 5
Column: 1
from sys import executable
from timeit import default_timer
from .common import Benchmark
class Import(Benchmark):
timer = default_timer
Reported by Pylint.
Line: 1
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b404-import-subprocess
from subprocess import call
from sys import executable
from timeit import default_timer
from .common import Benchmark
class Import(Benchmark):
timer = default_timer
Reported by Bandit.
Line: 1
Column: 1
from subprocess import call
from sys import executable
from timeit import default_timer
from .common import Benchmark
class Import(Benchmark):
timer = default_timer
Reported by Pylint.
Line: 8
Column: 1
from .common import Benchmark
class Import(Benchmark):
timer = default_timer
def execute(self, command):
call((executable, '-c', command))
Reported by Pylint.
Line: 11
Column: 5
class Import(Benchmark):
timer = default_timer
def execute(self, command):
call((executable, '-c', command))
def time_numpy(self):
self.execute('import numpy')
Reported by Pylint.
Line: 11
Column: 5
class Import(Benchmark):
timer = default_timer
def execute(self, command):
call((executable, '-c', command))
def time_numpy(self):
self.execute('import numpy')
Reported by Pylint.
Line: 12
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b603_subprocess_without_shell_equals_true.html
timer = default_timer
def execute(self, command):
call((executable, '-c', command))
def time_numpy(self):
self.execute('import numpy')
def time_numpy_inspect(self):
Reported by Bandit.
Line: 14
Column: 5
def execute(self, command):
call((executable, '-c', command))
def time_numpy(self):
self.execute('import numpy')
def time_numpy_inspect(self):
# What are the savings from avoiding to import the inspect module?
self.execute('import numpy, inspect')
Reported by Pylint.
Line: 17
Column: 5
def time_numpy(self):
self.execute('import numpy')
def time_numpy_inspect(self):
# What are the savings from avoiding to import the inspect module?
self.execute('import numpy, inspect')
def time_fft(self):
self.execute('from numpy import fft')
Reported by Pylint.
Line: 21
Column: 5
# What are the savings from avoiding to import the inspect module?
self.execute('import numpy, inspect')
def time_fft(self):
self.execute('from numpy import fft')
def time_linalg(self):
self.execute('from numpy import linalg')
Reported by Pylint.
doc/neps/tools/build_index.py
14 issues
Line: 14
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b701_jinja2_autoescape_false.html
def render(tpl_path, context):
path, filename = os.path.split(tpl_path)
return jinja2.Environment(
loader=jinja2.FileSystemLoader(path or './')
).get_template(filename).render(context)
def nep_metadata():
ignore = ('nep-template.rst')
Reported by Bandit.
Line: 32
Column: 30
print(f' - {source}')
nr = int(re.match(r'nep-([0-9]{4}).*\.rst', source).group(1))
with open(source) as f:
lines = f.readlines()
tags = [re.match(meta_re, line) for line in lines]
tags = [match.groups() for match in tags if match is not None]
tags = {tag[0]: tag[1] for tag in tags}
Reported by Pylint.
Line: 47
Column: 35
else:
raise RuntimeError("Unable to find NEP title.")
tags['Title'] = lines[i+1].strip()
tags['Filename'] = source
if not tags['Title'].startswith(f'NEP {nr} — '):
raise RuntimeError(
f'Title for NEP {nr} does not start with "NEP {nr} — " '
Reported by Pylint.
Line: 8
Column: 1
import os
import jinja2
import glob
import re
def render(tpl_path, context):
path, filename = os.path.split(tpl_path)
Reported by Pylint.
Line: 9
Column: 1
import os
import jinja2
import glob
import re
def render(tpl_path, context):
path, filename = os.path.split(tpl_path)
return jinja2.Environment(
Reported by Pylint.
Line: 12
Column: 1
import re
def render(tpl_path, context):
path, filename = os.path.split(tpl_path)
return jinja2.Environment(
loader=jinja2.FileSystemLoader(path or './')
).get_template(filename).render(context)
Reported by Pylint.
Line: 18
Column: 1
loader=jinja2.FileSystemLoader(path or './')
).get_template(filename).render(context)
def nep_metadata():
ignore = ('nep-template.rst')
sources = sorted(glob.glob(r'nep-*.rst'))
sources = [s for s in sources if not s in ignore]
meta_re = r':([a-zA-Z\-]*): (.*)'
Reported by Pylint.
Line: 18
Column: 1
loader=jinja2.FileSystemLoader(path or './')
).get_template(filename).render(context)
def nep_metadata():
ignore = ('nep-template.rst')
sources = sorted(glob.glob(r'nep-*.rst'))
sources = [s for s in sources if not s in ignore]
meta_re = r':([a-zA-Z\-]*): (.*)'
Reported by Pylint.
Line: 18
Column: 1
loader=jinja2.FileSystemLoader(path or './')
).get_template(filename).render(context)
def nep_metadata():
ignore = ('nep-template.rst')
sources = sorted(glob.glob(r'nep-*.rst'))
sources = [s for s in sources if not s in ignore]
meta_re = r':([a-zA-Z\-]*): (.*)'
Reported by Pylint.
Line: 30
Column: 9
print('Loading metadata for:')
for source in sources:
print(f' - {source}')
nr = int(re.match(r'nep-([0-9]{4}).*\.rst', source).group(1))
with open(source) as f:
lines = f.readlines()
tags = [re.match(meta_re, line) for line in lines]
tags = [match.groups() for match in tags if match is not None]
Reported by Pylint.