python / python/mypy

Incorrect error message for negative of numpy.sum

Open
#13,958 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

Not sure if this is rather an issue with numpy. I'm therefore posting this in both numpy and here:

When I take the negative of the sum of a array's elements by calling the numpy.sum function with a minus sign before (i.e. -numpy.sum(x)), I get the following error from mypy:

test.py:5: error: Unsupported operand type for unary - (<nothing>)
Found 1 error in 1 file (checked 1 source file)

However, calling the .sum-method on the array (which should be equivalent) gives no error. In both cases, the code works just fine. See below for code example

To Reproduce

import numpy as np


def fail(p: np.ndarray) -> float:
    return -np.sum(p)


def ok(p: np.ndarray) -> float:
    return -p.sum()


if __name__ == '__main__':
    print(fail(np.ones(3)))
    print(ok(np.ones(3)))

Expected Behavior

I would expect to errors for the above script and a message:

Success: no issues found in 1 source file

Actual Behavior

test.py:5: error: Unsupported operand type for unary - (<nothing>)
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 0.982 (compiled: yes)
  • Mypy command-line flags: none (except the source file)
  • Mypy configuration options from mypy.ini (and other config files):
[mypy]
plugins = numpy.typing.mypy_plugin
strict_optional = True
ignore_missing_imports = True
follow_imports = skip
  • Python version used: 3.8.10

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the reproduction in test.py using mypy 0.982 and the numpy.typing.mypy_plugin configuration. Compare type checking for -numpy.sum(p) with -p.sum() and investigate why the first expression is inferred as nothing. Done means the example produces no errors while preserving the existing behavior of both calls.

Written by the indexing model from the issue text.

Assessment

Tech stack
numpy, python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.