Rouben
Rouben

Reputation: 101

len() of np.array gives TypeError: len() of unsized object

I need to update a rather large python 2.7 project to python 3. Disclaimer, I'm new to python and this is a task I was given to learn the ins and outs of this language. The tricky part is the following:

assert ((nzis is None and shape is not None) or
            (nzis is not None and shape is None))

    # Set non-zero indices of the object mask's
    if nzis is None:
        self._nzis = shape_to_nzis(shape)
    else:
        self._nzis = np.array(nzis)

Later the following is called

assert len(self._nzis) <= MAX_NZIS_PER_ENTITY

It's that line, that gives me the error. Any ideas on what could be wrong? Note: The whole code works perfectly fine in Python2.7

Upvotes: 1

Views: 2125

Answers (1)

hpaulj
hpaulj

Reputation: 231530

Searching the web I found

https://github.com/vicariousinc/schema-games/blob/master/schema_games/utils.py

def shape_to_nzis(shape):
    """
    Convert a shape tuple (int, int) to NZIs.
    """
    return np.array(zip(*np.ones(shape).nonzero()))

In [48]: np.array(zip(*np.ones((3,4)).nonzero()))                               
Out[48]: array(<zip object at 0x7f39a009afc8>, dtype=object)
In [49]: len(_)                                                                 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-556fcc1c5d2a> in <module>
----> 1 len(_)

TypeError: len() of unsized object

In py3 that function needs to use:

In [50]: np.array(list(zip(*np.ones((3,4)).nonzero())))                         
Out[50]: 
array([[0, 0],
       [0, 1],
       [0, 2],
       [0, 3],
       [1, 0],
       [1, 1],
       [1, 2],
       [1, 3],
       [2, 0],
       [2, 1],
       [2, 2],
       [2, 3]])

Upvotes: 1

Related Questions