Skip to content

np.float64 is not accepted as float under static type checks #21906

Closed

Description

@0xjc

Some of the built-in scalar types inherit from the corresponding Python types. However, this fact does not seem to be exposed by the numpy type stubs.

# Python version 3.8.10, numpy version 1.23.0
import numpy as np

x = np.float64(1.0)
print(f"x={x} of type={type(x)} is float: {isinstance(x, float)}")
# x=1.0 of type=<class 'numpy.float64'> is float: True


def f(a: float) -> float:
    return a


f(x)
"""
pyright 1.1.256:
error: Argument of type "float64" cannot be assigned to parameter "a" of type "float" in function "f"
  "float64" is incompatible with "float" (reportGeneralTypeIssues)

mypy 0.961:
error: Argument 1 to "f" has incompatible type "floating[_64Bit]"; expected "float"
"""

Replacing np.float64 with np.float_ or np.double does not help.

Activity

  1. BvB93 commented on Jul 6, 2022

    @BvB93
    Member

    The bit issue here is that with current structure of the np.float64 annotations, i.e. it bring treated as parametrised np.floating type alias, that we cannot use different base classes for the likes of np.float64 and np.float32, the latter not inheriting from float during runtime. Replacing the type alias with a proper subclass is quite frankly not a viable solution, as thus would make it impractically difficult to do anything with all but a limited set of np.number subtype.

    So this leaves us with two options:

    • Maintain the status quo, i.e. don’t treat np.float64 as a float subtype.
    • Treat float as a np.floating subtype, even though this is not the case during runtime for the likes or np.float32. I recall there being discussion on this subject in the past; it might be worthwhile to reopen those.
  2. gerner commented on Sep 29, 2022

    @gerner

    I ran into this when I upgraded from numpy 1.21.x to 1.22.x. Is there a simple workaround to unblock static checks?

  3. satyanash commented on Nov 18, 2022

    @satyanash

    This is quite weird and breaks static type-checkers on a bunch of code that treats float and np.float64 as equivalent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions