dtracers
dtracers

Reputation: 1658

Convert numpy scalar to python simple native (with one twist)

I have a function that performs some operations and sets some protobuf values.

Now protobuf requires that the values that are set are python natives and not numpy values.

Now half the time this function is called with native values and half the time with numpy values.

I need a fullproof way to convert numpy values to native values while not causing an issue if the type is already a python native value.

What I tried:

using numpy.asscalar this fails when getting native values I have tried converting it to a string then back again but that feels very slow and a horrible way to perform this operation.

Upvotes: 1

Views: 349

Answers (1)

Ilja Everilä
Ilja Everilä

Reputation: 52947

You could write your own asscalar(), which tries to use np.asscalar() and reverts to just returning the value as is, if that fails:

import numpy as np

def asscalar(v):
    """
    Try converting a numpy array of size 1 to a scalar equivalent, or return
    the value as is.

    Returns:
        A scalar value, if a numpy array of size 1 was given, the value itself
        otherwise. Note that a python list of size 1 will be returned as is.

    Raises:
        A ValueError, if v is a numpy array of size larger than 1.
    """
    try:
        return np.asscalar(v)

    except AttributeError:
        # Not something numpy understands
        return v

Upvotes: 3

Related Questions