Skip to content

Commit c88e5bf

Browse files
committed
Merge pull request #239 in LCL/wolframclientforpython from bugfix/394303-dates to master
* commit 'd89815f7cea821cc5953364f9e18b7e9c2104590': adding more tests for shape and len adding test for generators array might have been a generator adding binary_deserialize load PackedArray must do the same _valid_type_or_fail now returns type code refactor using force_bytes for py2 compatibility using pack ability to serialiaze multiple values at once code refactor NumericArray is supposed to be initialized by a list of python numbers adding PackedArray benchmarks avoiding attribute lookup for every single element in the array speed optimizations in wxf serializer and zlib encoder
2 parents 0bc5d67 + d89815f commit c88e5bf

2 files changed

Lines changed: 29 additions & 4 deletions

File tree

wolframclient/language/array.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from __future__ import absolute_import, print_function, unicode_literals
22

33
import struct
4+
from functools import reduce
5+
from operator import mul
46

57
from wolframclient.exception import WolframLanguageException
68
from wolframclient.serializers.wxfencoder import constants
@@ -12,6 +14,10 @@
1214
from collections import Sequence
1315

1416

17+
def pack(format, *elements):
18+
return struct.pack(b"<%i%s" % (len(elements), force_bytes(format)), *elements)
19+
20+
1521
class NumericArray(Sequence):
1622
def __init__(self, array, type, shape=None):
1723

@@ -29,15 +35,14 @@ def _valid_type_or_fail(self, type):
2935
return type
3036

3137
def tobytes(self):
32-
return struct.pack(
33-
b"<%i%s" % (len(self), force_bytes(self.struct.format[1])), *self.array
34-
)
38+
return pack(self.struct.format[1], *self.array)
39+
3540

3641
def __getitem__(self, k):
3742
return self.array[k]
3843

3944
def __len__(self):
40-
return len(self.array)
45+
return reduce(mul, self.shape, 1)
4146

4247

4348
class PackedArray(NumericArray):

wolframclient/tests/serializers/wxf_pythonarray.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,23 @@ def test_python_array(self):
3030
export(arr, target_format="wxf"),
3131
export(NumericArray(array, wl_type, shape=shape), target_format="wxf"),
3232
)
33+
34+
def test_generators(self):
35+
36+
array = NumericArray((i for i in range(10)), "Integer8", shape=(10, ))
37+
38+
self.assertEqual(
39+
export(numpy.arange(10).astype(numpy.int8), target_format="wxf"),
40+
export(array, target_format="wxf"),
41+
)
42+
43+
self.assertEqual(len(array), 10)
44+
45+
array = NumericArray((i for i in range(10)), "Integer8", shape=(5, 2))
46+
47+
self.assertEqual(
48+
export(numpy.arange(10).astype(numpy.int8).reshape(5, 2), target_format="wxf"),
49+
export(array, target_format="wxf"),
50+
)
51+
52+
self.assertEqual(len(array), 10)

0 commit comments

Comments
 (0)