[SciPy-dev] asscalar and asarray in numpy

Hoyt Koepke hoytak@gmail....
Sat May 17 11:48:48 CDT 2008


Perhaps I'm misunderstanding things, I'm a bit surprised that asscalar
cannot take a scalar argument, i.e.

d = asscalar(1.0)

doesn't work.  Although the doc string specifies that it returns the
scalar part of a single element array, my assumption about this
method's behavior based on how asarray is used is that it should
accept anything that can be turned into a scalar and do the conversion
based on that, i.e. we can use it to ensure that a particular type is
a scalar.

The current code in the function is:

def asscalar(a):
    """Convert an array of size 1 to its scalar equivalent.
    return a.item()

I'm thinking it would be reasonable to replace this by something more
robust, perhaps:

def asscalar(a):
    """Convert the input to its scalar equivalent, if possible.
    if numpy.isscalar(a):
        return a
    elif isinstance(a, numpy.ndarray):
        return a.item()
        raise TypeError("Argument cannot be converted to a scalar.")

This is untested, and I may be missing subtleties in how I'm doing
this -- if so, let me know.  I'd be happy to write a unit test if
people want this change.

Those worried about speed can just use the a.item() method directly.

Am I misunderstanding the reasoning behind the as* functions, or is
this reasonable?


Hoyt Koepke
UBC Department of Computer Science

More information about the Scipy-dev mailing list