0

I have a function of an integer and a numpy array. It accepts a single int and a 1D array, or alternatively it accepts an array of ints and a 2D array which are then broadcast, e.g.

def norm_matrix(l, cov):
    norm_cov = cov / (l*(l+1))
    return norm_cov

My question is how to write the type hints in this case. Does this work?

def norm_matrix(
    l: Union[int, np.ndarray],
    cov: np.ndarray
):

and is there a better way to do it?

2 Answers 2

1

Your solution coul be improved by using numpy.typing.NDarray From the typing module of numpy

Sign up to request clarification or add additional context in comments.

Comments

1

Your way is correct. It is the default way.

If you find it too cumbersome you can do use the bitwise operator | instead as mentioned in the Union documentation:

l: int | np.ndarray

But generally in Python we frown upon mixing input types since it complicates things. But like all rules, this one has an exception: multimethods - Here is an article by Guido explaining how they work.

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.