Search code examples
pythonnumpycastingtype-hintingpyright

(Python, Numpy: type hinting), How to correctly convert "integer" value to "_DType@clip"?


I'm having trouble with Numpy (version 1.25) Type hinting. Suppose following code (/tmp/asdf.py):

import numpy as np

tx: int = 32 
out_tx = np.clip(
        tx,
        0, 
        100,
        )

pyright is giving me following errors:

$ pyright /tmp/asdf.py
/tmp/asdf.py
  /tmp/asdf.py:5:9 - error: Argument of type "Literal[32]" cannot be assigned to parameter "a" of type "ndarray[_DType@clip]" in function "clip"
    "Literal[32]" is incompatible with "ndarray[_DType@clip]" (reportGeneralTypeIssues)
  /tmp/asdf.py:6:9 - error: Argument of type "Literal[0]" cannot be assigned to parameter "a_min" of type "_DType@clip" in function "clip"
    Type "Literal[0]" is incompatible with constrained type variable "_DType" (reportGeneralTypeIssues)
  /tmp/asdf.py:7:9 - error: Argument of type "Literal[100]" cannot be assigned to parameter "a_max" of type "_DType@clip" in function "clip"
    Type "Literal[100]" is incompatible with constrained type variable "_DType" (reportGeneralTypeIssues)
3 errors, 0 warnings, 0 informations
  • How to correctly convert in Literal "integer" into Numpy's "_DType@clip", such that pyright won't output this messages?

Update:

  • I forgot to mention that I'm on numpy v1.25.
  • On numpy v.1.24, pyright doesn't output any warning
  • I know that above code works.
  • I was just looking for the safest way to write, because I really like static-analyzers/linters/LSPs.

Solution

  • I found why pyright was outputting error when it shouldn't have output an error:

    The reason was that I also installed data-science-types package. And it seems it has override numpy's typing.

    After uninstalling it (with pip3 uninstall data-science-types) pyright doesn't output this error again.