So geben Sie eine Hinweisfunktion ein, um mit Numpy kompatibel zu seinPython

Python-Programme
Guest
 So geben Sie eine Hinweisfunktion ein, um mit Numpy kompatibel zu sein

Post by Guest »

Quellcode von example.py:

Code: Select all

from typing import Union, Any
import numpy as np

Number = Union[int, float, np.floating[Any]]

def add_one(num: Number) -> Number:
return num + 1

inputs = [1, 2, 3]
outputs = [add_one(n) for n in inputs]

avg = np.mean(outputs)
Führen Sie mypy aus:

Code: Select all

mypy example.py
src/example.py:14: error: Argument 1 to "mean" has incompatible type "List[Union[float, floating[Any]]]"; expected "Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, _NestedSequence[Union[bool, int, float, complex, str, bytes]]]"
Found 1 error in 1 file (checked 1 source file)
Ich kann alles in np.floating[Any] ändern, was das Numpy-Problem behebt, aber dann muss ich Grundelemente in np.float32(...) umwandeln:

Code: Select all

from typing import Any
import numpy as np

def add_one(num: np.floating[Any]) -> np.floating[Any]:
return num + 1

inputs = [1, 2, 3]
outputs = [add_one(np.float32(n)) for n in inputs]

avg = np.mean(outputs)
Gibt es eine korrekte Möglichkeit, einen Hinweis auf die Funktion add_one einzugeben, sodass ihre Ausgaben mit Numpy-Funktionen wie np.mean kompatibel sind ohne die Kompatibilität zu beeinträchtigen? mit den Python-Primitivtypen? Das Endziel besteht darin, es wie folgt verwenden zu können:

Code: Select all

inputs = [1, 2, 3]
outputs = [add_one(n) for n in inputs]
avg = np.mean(outputs)

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post