/
coretypes.py
1441 lines (1133 loc) · 38.2 KB
/
coretypes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
"""
This defines the DataShape type system, with unified
shape and data type.
"""
import sys
import ctypes
import operator
from math import ceil
import datashape
import numpy as np
from .py2help import (
OrderedDict,
_inttypes,
_strtypes,
basestring,
unicode,
with_metaclass,
)
from .internal_utils import IndexCallable, isidentifier
# Classes of unit types.
DIMENSION = 1
MEASURE = 2
class Type(type):
_registry = {}
def __new__(meta, name, bases, dct):
cls = super(Type, meta).__new__(meta, name, bases, dct)
# Don't register abstract classes
if not dct.get('abstract'):
Type._registry[name] = cls
return cls
@classmethod
def register(cls, name, type):
# Don't clobber existing types.
if name in cls._registry:
raise TypeError('There is another type registered with name %s'
% name)
cls._registry[name] = type
@classmethod
def lookup_type(cls, name):
return cls._registry[name]
class Mono(with_metaclass(Type, object)):
"""
Monotype are unqualified 0 parameters.
Each type must be reconstructable using its parameters:
type(datashape_type)(*type.parameters)
"""
composite = False
def __init__(self, *params):
self._parameters = params
@property
def _slotted(self):
return hasattr(self, '__slots__')
@property
def parameters(self):
if self._slotted:
return tuple(getattr(self, slot) for slot in self.__slots__)
else:
return self._parameters
def info(self):
return type(self), self.parameters
def __eq__(self, other):
return (isinstance(other, Mono) and
self.shape == other.shape and
self.measure.info() == other.measure.info())
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
try:
h = self._hash
except AttributeError:
h = self._hash = hash(self.shape) ^ hash(self.measure.info())
return h
@property
def shape(self):
return ()
def __len__(self):
return 1
def __getitem__(self, key):
return [self][key]
def __repr__(self):
return '%s(%s)' % (
type(self).__name__,
', '.join(
(
'%s=%r' % (slot, getattr(self, slot))
for slot in self.__slots__
) if self._slotted else
map(repr, self.parameters),
),
)
# Monotypes are their own measure
@property
def measure(self):
return self
def subarray(self, leading):
"""Returns a data shape object of the subarray with 'leading'
dimensions removed. In the case of a measure such as CType,
'leading' must be 0, and self is returned.
"""
if leading >= 1:
raise IndexError(('Not enough dimensions in data shape '
'to remove %d leading dimensions.') % leading)
else:
return self
def __mul__(self, other):
if isinstance(other, _strtypes):
import datashape
return datashape.dshape(other).__rmul__(self)
if isinstance(other, _inttypes):
other = Fixed(other)
if isinstance(other, DataShape):
return other.__rmul__(self)
return DataShape(self, other)
def __rmul__(self, other):
if isinstance(other, _strtypes):
import datashape
return self * datashape.dshape(other)
if isinstance(other, _inttypes):
other = Fixed(other)
return DataShape(other, self)
def __getstate__(self):
return self.parameters
def __setstate__(self, state):
if self._slotted:
for slot, val in zip(self.__slots__, state):
setattr(self, slot, val)
else:
self._parameters = state
def to_numpy_dtype(self):
raise TypeError('DataShape %s is not NumPy-compatible' % self)
class Unit(Mono):
"""
Unit type that does not need to be reconstructed.
"""
def __str__(self):
return type(self).__name__.lower()
class Ellipsis(Mono):
"""Ellipsis (...). Used to indicate a variable number of dimensions.
E.g.:
... * float32 # float32 array w/ any number of dimensions
A... * float32 # float32 array w/ any number of dimensions,
# associated with type variable A
"""
__slots__ = 'typevar',
def __init__(self, typevar=None):
self.typevar = typevar
def __str__(self):
return str(self.typevar) + '...' if self.typevar else '...'
def __repr__(self):
return '%s(%r)' % (type(self).__name__, str(self))
class Null(Unit):
"""The null datashape."""
pass
class Date(Unit):
""" Date type """
cls = MEASURE
__slots__ = ()
def to_numpy_dtype(self):
return np.dtype('datetime64[D]')
class Time(Unit):
""" Time type """
cls = MEASURE
__slots__ = 'tz',
def __init__(self, tz=None):
if tz is not None and not isinstance(tz, _strtypes):
raise TypeError('tz parameter to time datashape must be a string')
# TODO validate against Olson tz database
self.tz = tz
def __str__(self):
basename = super(Time, self).__str__()
if self.tz is None:
return basename
else:
return '%s[tz=%r]' % (basename, str(self.tz))
class DateTime(Unit):
""" DateTime type """
cls = MEASURE
__slots__ = 'tz',
def __init__(self, tz=None):
if tz is not None and not isinstance(tz, _strtypes):
raise TypeError('tz parameter to datetime datashape must be a '
'string')
# TODO validate against Olson tz database
self.tz = tz
def __str__(self):
basename = super(DateTime, self).__str__()
if self.tz is None:
return basename
else:
return '%s[tz=%r]' % (basename, str(self.tz))
def to_numpy_dtype(self):
return np.dtype('datetime64[us]')
_units = set(['ns', 'us', 'ms', 's', 'm', 'h', 'D', 'W', 'M', 'Y'])
_unit_aliases = {
'year': 'Y',
'week': 'W',
'day': 'D',
'date': 'D',
'hour': 'h',
'second': 's',
'millisecond': 'ms',
'microsecond': 'us',
'nanosecond': 'ns'
}
def normalize_time_unit(s):
""" Normalize time input to one of 'year', 'second', 'millisecond', etc..
Example
-------
>>> normalize_time_unit('milliseconds')
'ms'
>>> normalize_time_unit('ms')
'ms'
>>> normalize_time_unit('nanoseconds')
'ns'
>>> normalize_time_unit('nanosecond')
'ns'
"""
s = s.strip()
if s in _units:
return s
if s in _unit_aliases:
return _unit_aliases[s]
if s[-1] == 's' and len(s) > 2:
return normalize_time_unit(s.rstrip('s'))
raise ValueError("Do not understand time unit %s" % s)
class TimeDelta(Unit):
cls = MEASURE
__slots__ = 'unit',
def __init__(self, unit='us'):
self.unit = normalize_time_unit(str(unit))
def __str__(self):
return 'timedelta[unit=%r]' % self.unit
def to_numpy_dtype(self):
return np.dtype('timedelta64[%s]' % self.unit)
class Units(Unit):
""" Units type for values with physical units """
cls = MEASURE
__slots__ = 'unit', 'tp'
def __init__(self, unit, tp=None):
if not isinstance(unit, _strtypes):
raise TypeError('unit parameter to units datashape must be a '
'string')
if tp is None:
tp = DataShape(float64)
elif not isinstance(tp, DataShape):
raise TypeError('tp parameter to units datashape must be a '
'datashape type')
self.unit = unit
self.tp = tp
def __str__(self):
if self.tp == DataShape(float64):
return 'units[%r]' % (self.unit)
else:
return 'units[%r, %s]' % (self.unit, self.tp)
class Bytes(Unit):
""" Bytes type """
cls = MEASURE
__slots__ = ()
_canonical_string_encodings = {
u'A': u'A',
u'ascii': u'A',
u'U8': u'U8',
u'utf-8': u'U8',
u'utf_8': u'U8',
u'utf8': u'U8',
u'U16': u'U16',
u'utf-16': u'U16',
u'utf_16': u'U16',
u'utf16': u'U16',
u'U32': u'U32',
u'utf-32': u'U32',
u'utf_32': u'U32',
u'utf32': u'U32',
}
class String(Unit):
""" String container
>>> String()
ctype("string")
>>> String(10, 'ascii')
ctype("string[10, 'A']")
"""
cls = MEASURE
__slots__ = 'fixlen', 'encoding'
def __init__(self, *args):
if len(args) == 0:
fixlen, encoding = None, None
if len(args) == 1:
if isinstance(args[0], _strtypes):
fixlen, encoding = None, args[0]
if isinstance(args[0], _inttypes):
fixlen, encoding = args[0], None
if len(args) == 2:
fixlen, encoding = args
encoding = encoding or 'U8'
if isinstance(encoding, str):
encoding = unicode(encoding)
try:
encoding = _canonical_string_encodings[encoding]
except KeyError:
raise ValueError('Unsupported string encoding %s' %
repr(encoding))
self.encoding = encoding
self.fixlen = fixlen
# Put it in a canonical form
def __str__(self):
if self.fixlen is None and self.encoding == 'U8':
return 'string'
elif self.fixlen is not None and self.encoding == 'U8':
return 'string[%i]' % self.fixlen
elif self.fixlen is None and self.encoding != 'U8':
return 'string[%s]' % repr(self.encoding).strip('u')
else:
return 'string[%i, %s]' % (self.fixlen,
repr(self.encoding).strip('u'))
def __repr__(self):
s = str(self)
return 'ctype("%s")' % s.encode('unicode_escape').decode('ascii')
def to_numpy_dtype(self):
"""
>>> String().to_numpy_dtype()
dtype('O')
>>> String(30).to_numpy_dtype()
dtype('<U30')
>>> String(30, 'A').to_numpy_dtype()
dtype('S30')
"""
if self.fixlen:
if self.encoding == 'A':
return np.dtype('S%d' % self.fixlen)
else:
return np.dtype('U%d' % self.fixlen)
from .py2help import unicode
# Create a dtype with metadata indicating it's
# a string in the same style as the h5py special_dtype
return np.dtype('O', metadata={'vlen': unicode})
class Decimal(Unit):
"""Decimal type corresponding to SQL Decimal/Numeric types.
The first parameter passed specifies the number of digits of precision that
the Decimal contains. If an additional parameter is given, it represents
the scale, or number of digits of precision that are after the decimal
point.
The Decimal type makes no requirement of how it is to be stored in memory,
therefore, the number of bytes needed to store a Decimal for a given
precision will vary based on the platform where it is used.
Examples
--------
>>> Decimal(18)
Decimal(precision=18, scale=0)
>>> Decimal(7, 4)
Decimal(precision=7, scale=4)
>>> Decimal(precision=11, scale=2)
Decimal(precision=11, scale=2)
"""
cls = MEASURE
__slots__ = 'precision', 'scale'
def __init__(self, precision, scale=0):
self.precision = precision
self.scale = scale
def __str__(self):
return 'decimal[precision={precision}, scale={scale}]'.format(
precision=self.precision, scale=self.scale
)
def to_numpy_dtype(self):
"""Convert a decimal datashape to a NumPy dtype.
Note that floating-point (scale > 0) precision will be lost converting
to NumPy floats.
Examples
--------
>>> Decimal(18).to_numpy_dtype()
dtype('int64')
>>> Decimal(7,4).to_numpy_dtype()
dtype('float64')
"""
if self.scale == 0:
if self.precision <= 2:
return np.dtype(np.int8)
elif self.precision <= 4:
return np.dtype(np.int16)
elif self.precision <= 9:
return np.dtype(np.int32)
elif self.precision <= 18:
return np.dtype(np.int64)
else:
raise TypeError(
'Integer Decimal precision > 18 is not NumPy-compatible')
else:
return np.dtype(np.float64)
class DataShape(Mono):
"""
Composite container for datashape elements.
Elements of a datashape like ``Fixed(3)``, ``Var()`` or ``int32`` are on,
on their own, valid datashapes. These elements are collected together into
a composite ``DataShape`` to be complete.
This class is not intended to be used directly. Instead, use the utility
``dshape`` function to create datashapes from strings or datashape
elements.
Examples
--------
>>> from datashape import Fixed, int32, DataShape, dshape
>>> DataShape(Fixed(5), int32) # Rare to DataShape directly
dshape("5 * int32")
>>> dshape('5 * int32') # Instead use the dshape function
dshape("5 * int32")
>>> dshape([Fixed(5), int32]) # It can even do construction from elements
dshape("5 * int32")
See Also
--------
datashape.dshape
"""
composite = False
def __init__(self, *parameters, **kwds):
if len(parameters) == 1 and isinstance(parameters[0], _strtypes):
raise TypeError("DataShape constructor for internal use.\n"
"Use dshape function to convert strings into "
"datashapes.\nTry:\n\tdshape('%s')"
% parameters[0])
if len(parameters) > 0:
self._parameters = tuple(map(_launder, parameters))
if getattr(self._parameters[-1], 'cls', MEASURE) != MEASURE:
raise TypeError(('Only a measure can appear on the'
' last position of a datashape, not %s') %
repr(self._parameters[-1]))
for dim in self._parameters[:-1]:
if getattr(dim, 'cls', DIMENSION) != DIMENSION:
raise TypeError(('Only dimensions can appear before the'
' last position of a datashape, not %s') %
repr(dim))
else:
raise ValueError('the data shape should be constructed from 2 or'
' more parameters, only got %s' % len(parameters))
self.composite = True
self.name = kwds.get('name')
if self.name:
type(type(self))._registry[self.name] = self
def __len__(self):
return len(self.parameters)
def __getitem__(self, index):
return self.parameters[index]
def __str__(self):
return self.name or ' * '.join(map(str, self.parameters))
def __repr__(self):
s = pprint(self)
if '\n' in s:
return 'dshape("""%s""")' % s
else:
return 'dshape("%s")' % s
@property
def shape(self):
return self.parameters[:-1]
@property
def measure(self):
return self.parameters[-1]
def subarray(self, leading):
"""Returns a data shape object of the subarray with 'leading'
dimensions removed.
>>> from datashape import dshape
>>> dshape('1 * 2 * 3 * int32').subarray(1)
dshape("2 * 3 * int32")
>>> dshape('1 * 2 * 3 * int32').subarray(2)
dshape("3 * int32")
"""
if leading >= len(self.parameters):
raise IndexError('Not enough dimensions in data shape '
'to remove %d leading dimensions.' % leading)
elif leading in [len(self.parameters) - 1, -1]:
return DataShape(self.parameters[-1])
else:
return DataShape(*self.parameters[leading:])
def __rmul__(self, other):
if isinstance(other, _inttypes):
other = Fixed(other)
return DataShape(other, *self)
@property
def subshape(self):
return IndexCallable(self._subshape)
def _subshape(self, index):
""" The DataShape of an indexed subarray
>>> from datashape import dshape
>>> ds = dshape('var * {name: string, amount: int32}')
>>> print(ds.subshape[0])
{name: string, amount: int32}
>>> print(ds.subshape[0:3])
3 * {name: string, amount: int32}
>>> print(ds.subshape[0:7:2, 'amount'])
4 * int32
>>> print(ds.subshape[[1, 10, 15]])
3 * {name: string, amount: int32}
>>> ds = dshape('{x: int, y: int}')
>>> print(ds.subshape['x'])
int32
>>> ds = dshape('10 * var * 10 * int32')
>>> print(ds.subshape[0:5, 0:3, 5])
5 * 3 * int32
>>> ds = dshape('var * {name: string, amount: int32, id: int32}')
>>> print(ds.subshape[:, [0, 2]])
var * {name: string, id: int32}
>>> ds = dshape('var * {name: string, amount: int32, id: int32}')
>>> print(ds.subshape[:, ['name', 'id']])
var * {name: string, id: int32}
>>> print(ds.subshape[0, 1:])
{amount: int32, id: int32}
"""
from .predicates import isdimension
if isinstance(index, _inttypes) and isdimension(self[0]):
return self.subarray(1)
if isinstance(self[0], Record) and isinstance(index, _strtypes):
return self[0][index]
if isinstance(self[0], Record) and isinstance(index, _inttypes):
return self[0].parameters[0][index][1]
if isinstance(self[0], Record) and isinstance(index, list):
rec = self[0]
# Translate strings to corresponding integers
index = [self[0].names.index(i) if isinstance(i, _strtypes) else i
for i in index]
return DataShape(Record([rec.parameters[0][i] for i in index]))
if isinstance(self[0], Record) and isinstance(index, slice):
rec = self[0]
return DataShape(Record(rec.parameters[0][index]))
if isinstance(index, list) and isdimension(self[0]):
return len(index) * self.subarray(1)
if isinstance(index, slice):
if isinstance(self[0], Fixed):
n = int(self[0])
start = index.start or 0
stop = index.stop or n
if start < 0:
start = n + start
if stop < 0:
stop = n + stop
count = stop - start
else:
start = index.start or 0
stop = index.stop
if not stop:
count = -start if start < 0 else var
if (stop is not None and start is not None and stop >= 0 and
start >= 0):
count = stop - start
else:
count = var
if count != var and index.step is not None:
count = int(ceil(count / index.step))
return count * self.subarray(1)
if isinstance(index, tuple):
if not index:
return self
elif index[0] is None:
return 1 * self._subshape(index[1:])
elif len(index) == 1:
return self._subshape(index[0])
else:
ds = self.subarray(1)._subshape(index[1:])
return (self[0] * ds)._subshape(index[0])
raise TypeError('invalid index value %s of type %r' %
(index, type(index).__name__))
def __setstate__(self, state):
self.__init__(*state)
numpy_provides_missing = frozenset((Date, DateTime, TimeDelta))
class Option(Mono):
"""
Measure types which may or may not hold data. Makes no
indication of how this is implemented in memory.
"""
__slots__ = 'ty',
def __init__(self, ds):
self.ty = _launder(ds)
@property
def shape(self):
return self.ty.shape
@property
def itemsize(self):
return self.ty.itemsize
def __str__(self):
return '?%s' % self.ty
def to_numpy_dtype(self):
if type(self.ty) in numpy_provides_missing:
return self.ty.to_numpy_dtype()
raise TypeError('DataShape measure %s is not NumPy-compatible' % self)
class CType(Unit):
"""
Symbol for a sized type mapping uniquely to a native type.
"""
cls = MEASURE
__slots__ = 'name', '_itemsize', '_alignment'
def __init__(self, name, itemsize, alignment):
self.name = name
self._itemsize = itemsize
self._alignment = alignment
Type.register(name, self)
@classmethod
def from_numpy_dtype(self, dt):
"""
From Numpy dtype.
>>> from datashape import CType
>>> from numpy import dtype
>>> CType.from_numpy_dtype(dtype('int32'))
ctype("int32")
>>> CType.from_numpy_dtype(dtype('i8'))
ctype("int64")
>>> CType.from_numpy_dtype(dtype('M8'))
DateTime(tz=None)
>>> CType.from_numpy_dtype(dtype('U30'))
ctype("string[30, 'U32']")
"""
try:
return Type.lookup_type(dt.name)
except KeyError:
pass
if np.issubdtype(dt, np.datetime64):
unit, _ = np.datetime_data(dt)
defaults = {'D': date_, 'Y': date_, 'M': date_, 'W': date_}
return defaults.get(unit, datetime_)
elif np.issubdtype(dt, np.timedelta64):
unit, _ = np.datetime_data(dt)
return TimeDelta(unit=unit)
elif np.issubdtype(dt, np.unicode_):
return String(dt.itemsize // 4, 'U32')
elif np.issubdtype(dt, np.str_) or np.issubdtype(dt, np.bytes_):
return String(dt.itemsize, 'ascii')
raise NotImplementedError("NumPy datatype %s not supported" % dt)
@property
def itemsize(self):
"""The size of one element of this type."""
return self._itemsize
@property
def alignment(self):
"""The alignment of one element of this type."""
return self._alignment
def to_numpy_dtype(self):
"""
To Numpy dtype.
"""
# TODO: Fixup the complex type to how numpy does it
name = self.name
return np.dtype({
'complex[float32]': 'complex64',
'complex[float64]': 'complex128'
}.get(name, name))
def __str__(self):
return self.name
def __repr__(self):
s = str(self)
return 'ctype("%s")' % s.encode('unicode_escape').decode('ascii')
class Fixed(Unit):
"""
Fixed dimension.
"""
cls = DIMENSION
__slots__ = 'val',
def __init__(self, i):
# Use operator.index, so Python integers, numpy int scalars, etc work
i = operator.index(i)
if i < 0:
raise ValueError('Fixed dimensions must be positive')
self.val = i
def __index__(self):
return self.val
def __int__(self):
return self.val
def __eq__(self, other):
return (type(other) is Fixed and self.val == other.val or
isinstance(other, _inttypes) and self.val == other)
__hash__ = Mono.__hash__
def __str__(self):
return str(self.val)
class Var(Unit):
""" Variable dimension """
cls = DIMENSION
__slots__ = ()
class TypeVar(Unit):
"""
A free variable in the signature. Not user facing.
"""
# cls could be MEASURE or DIMENSION, depending on context
__slots__ = 'symbol',
def __init__(self, symbol):
if not symbol[0].isupper():
raise ValueError(('TypeVar symbol %r does not '
'begin with a capital') % symbol)
self.symbol = symbol
def __str__(self):
return str(self.symbol)
class Function(Mono):
"""Function signature type
"""
@property
def restype(self):
return self.parameters[-1]
@property
def argtypes(self):
return self.parameters[:-1]
def __str__(self):
return '(%s) -> %s' % (
', '.join(map(str, self.argtypes)), self.restype
)
class Map(Mono):
__slots__ = 'key', 'value'
def __init__(self, key, value):
self.key = _launder(key)
self.value = _launder(value)
def __str__(self):
return '%s[%s, %s]' % (type(self).__name__.lower(),
self.key,
self.value)
def to_numpy_dtype(self):
return to_numpy_dtype(self)
def _launder(x):
""" Clean up types prior to insertion into DataShape
>>> from datashape import dshape
>>> _launder(5) # convert ints to Fixed
Fixed(val=5)
>>> _launder('int32') # parse strings
ctype("int32")
>>> _launder(dshape('int32'))
ctype("int32")
>>> _launder(Fixed(5)) # No-op on valid parameters
Fixed(val=5)
"""
if isinstance(x, _inttypes):
x = Fixed(x)
if isinstance(x, _strtypes):
return Type.lookup_type(x)
if isinstance(x, DataShape) and len(x) == 1:
return x[0]
return x
class CollectionPrinter(object):
def __repr__(self):
s = str(self)
strs = ('"""%s"""' if '\n' in s else '"%s"') % s
return 'dshape(%s)' % strs
class RecordMeta(Type):
@staticmethod
def _unpack_slice(s, idx):
if not isinstance(s, slice):
raise TypeError(
'invalid field specification at position %d.\n'
'fields must be formatted like: {name}:{type}' % idx,
)
name, type_ = packed = s.start, s.stop
if name is None:
raise TypeError('missing field name at position %d' % idx)
if not isinstance(name, basestring):
raise TypeError(
"field name at position %d ('%s') was not a string" % (
idx, name,
),
)
if type_ is None and s.step is None:
raise TypeError(
"missing type for field '%s' at position %d" % (name, idx))
if s.step is not None:
raise TypeError(
"unexpected slice step for field '%s' at position %d.\n"
"hint: you might have a second ':'" % (name, idx),
)
return packed
def __getitem__(self, types):
if not isinstance(types, tuple):
types = types,
return self(list(map(self._unpack_slice, types, range(len(types)))))
if sys.version_info[:2] == (2, 7):
def unify_name_types(names):
""" Construct the names of fields in a Record datashape to have a single
string type
Parameters
----------
names : list[str|unicode]
List of field names for a Record datashape
Returns
-------
list[str|unicode]
A list of strings of a *single* type: either str (Python 2 and 3)
or unicode (Python 2 only)
Examples
--------
>>> unify_name_types([u'a', 'b']) == list(u'ab')
True
>>> unify_name_types(list('ab')) == list('ab')