Skip to content

TypeError : len() of unsized object at algorithm_postsimulation.py:108 #130

@fdobad

Description

@fdobad

A len() of numpy.loadtxt() instance fails.
numpy version : '2.3.5'

diagnostic:

#!python3
from pprint import pprint

import numpy as np

test = {
    "rows": """"simid","cellid"
1,2
3,4
""",
    "row": """"simid","cellid"
1,2
""",
    "empty": "",
    "halfsemicolon": """"simid","cellid"
1,
""",
    "half": """"simid","cellid"
1
""",
}
pprint(test)

for k, v in test.items():
    print(f"--- {k} ---")
    open(k, "w").write(v)
    try:
        data = np.loadtxt(k, delimiter=",", skiprows=1, usecols=[0, 1], dtype=[("sim", np.int32), ("cellid", np.int32)])
    except Exception as e:
        print(f"error loading: {e}")
        continue

    if hasattr(data, "size"):
        print(f"size: {data.size}")
    if hasattr(data, "__len__"):
        try:
            print(f"len: {len(data)}")
        except Exception as e:
            if e is TypeError("len() of unsized object"):
                print(e.__traceback__)
            else:
                print("issue getting len()")

yields:

--- rows ---
size: 2
len: 2
--- row ---
size: 1
issue getting len()
--- empty ---
<ipython-input-36-c2f322146b24>:5: UserWarning: loadtxt: input contained no data: "empty"
  data = np.loadtxt(k, delimiter=",", skiprows=1, usecols=[0, 1], dtype=[("sim", np.int32), ("cellid", np.int32)])
size: 0
len: 0
--- halfsemicolon ---
error loading: could not convert string '' to int32 at row 0, column 2.
--- half ---
error loading: invalid column index 1 at row 1 with 1 columns

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions