Skip to content

Commit

Permalink
allow to init with shape, just like a numpy.recarray
Browse files Browse the repository at this point in the history
  • Loading branch information
relleums committed Jul 11, 2024
1 parent 7366a57 commit e1a1c7e
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 12 deletions.
29 changes: 18 additions & 11 deletions dynamicsizerecarray/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class DynamicSizeRecarray:
A dynamic, appendable implementation of numpy.core.records.recarray.
"""

def __init__(self, recarray=None, dtype=None):
def __init__(self, recarray=None, dtype=None, shape=0):
"""
Either provide an existing recarray 'recarray' or
provide the 'dtype' to start with an empty recarray.
Expand All @@ -19,6 +19,8 @@ def __init__(self, recarray=None, dtype=None):
The start of the dynamic recarray.
dtype : list(tuple("key", "dtype_str")), default=None
The dtype of the dynamic recarray.
shape : int
The initial size. (Same as in np.core.records.recarray)
"""
self._size = 0
if recarray is None and dtype == None:
Expand All @@ -28,19 +30,24 @@ def __init__(self, recarray=None, dtype=None):
"Expected either one of 'recarray' or' dtype' to be 'None'"
)

_minimal_capacity = 2

if dtype:
recarray = np.core.records.recarray(
shape=0,
if shape < 0:
raise AttributeError("Expected shape >= 0.")
initial_capacity = np.max([_minimal_capacity, shape])
self._recarray = np.core.records.recarray(
shape=initial_capacity,
dtype=dtype,
)

_minimal_capacity = 2
initial_capacity = np.max([_minimal_capacity, len(recarray)])
self._recarray = np.core.records.recarray(
shape=initial_capacity,
dtype=recarray.dtype,
)
self.append_recarray(recarray=recarray)
self._size = shape
else:
initial_capacity = np.max([_minimal_capacity, len(recarray)])
self._recarray = np.core.records.recarray(
shape=initial_capacity,
dtype=recarray.dtype,
)
self.append_recarray(recarray=recarray)

@property
def shape(self):
Expand Down
21 changes: 21 additions & 0 deletions dynamicsizerecarray/tests/test_init_shape.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import dynamicsizerecarray
import pytest
import numpy as np

def test_init_with_shape():
dra = dynamicsizerecarray.DynamicSizeRecarray(
dtype=[("a", "i8"), ("b", "u2")],
shape=13,
)

assert len(dra) == 13
assert dra._capacity() == 13


def test_init_negative_shape():
with pytest.raises(AttributeError):
dra = dynamicsizerecarray.DynamicSizeRecarray(
dtype=[("a", "i8")],
shape=-1,
)

2 changes: 1 addition & 1 deletion dynamicsizerecarray/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.0.9"
__version__ = "0.0.10"

0 comments on commit e1a1c7e

Please sign in to comment.