0

Is there a way to restrict the type of function input in python or I should always convert the input NumPy array to be float 32 array if I want?

I am trying to restrict the function input argument type to be a float 32 NumPy array. I have try something like below:

import numpy as np

def f(input : np.float32):
    return input*2

However, if I give an int NumPy array, the function is still work and return an int array.

1 Answer 1

1

Read more about Python Annotations here PEP3107.

Annotations doesn't force the function to accept input as the specified type.

Access annotations by, print(f.__annotations__) in your case.

You can use yourlist.astype(np.float32) to force the list argument to be NumPy float32.

def f(input : np.float32)-> np.float32:
    return input.astype(np.float32)*2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.