postyp 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- postyp-0.2.0/.gitignore +17 -0
- postyp-0.2.0/PKG-INFO +39 -0
- postyp-0.2.0/README.md +21 -0
- postyp-0.2.0/postyp.py +546 -0
- postyp-0.2.0/pyproject.toml +38 -0
postyp-0.2.0/.gitignore
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
__pycache__/
|
|
2
|
+
*.py[cod]
|
|
3
|
+
*.so
|
|
4
|
+
*.dylib
|
|
5
|
+
*.o
|
|
6
|
+
*.c.tmp
|
|
7
|
+
dist/
|
|
8
|
+
build/
|
|
9
|
+
*.egg-info/
|
|
10
|
+
.pytest_cache/
|
|
11
|
+
.claude/
|
|
12
|
+
# Pixi: the env dir is local; pixi.lock is committed for reproducibility.
|
|
13
|
+
.pixi/
|
|
14
|
+
# MkDocs build output
|
|
15
|
+
site/
|
|
16
|
+
# Local release artifacts
|
|
17
|
+
release-dist/
|
postyp-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: postyp
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: POST Python type vocabulary: scalar dtypes, Array, Shape, layouts, DataFrame and Series annotations.
|
|
5
|
+
Project-URL: Repository, https://github.com/openteams-ai/postpython
|
|
6
|
+
Project-URL: Specification, https://github.com/openteams-ai/postpython/blob/main/docs/spec.md
|
|
7
|
+
Project-URL: Website, https://post-py.org/
|
|
8
|
+
Author: Travis E. Oliphant
|
|
9
|
+
Keywords: array-api,dtypes,post-python,types
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering
|
|
15
|
+
Classifier: Topic :: Software Development :: Compilers
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# postyp
|
|
20
|
+
|
|
21
|
+
The [POST Python](https://post-py.org/) type vocabulary: scalar dtypes
|
|
22
|
+
(`Float64`, `Int64`, `Bool`, …), `Array` with `Shape` and layout
|
|
23
|
+
qualifiers, and `DataFrame`/`Series` annotations.
|
|
24
|
+
|
|
25
|
+
`postyp` is the canonical, compiler-independent source of POST Python
|
|
26
|
+
type metadata (spec §10). Conforming compilers introspect this module
|
|
27
|
+
rather than duplicating dtype definitions; POST source files import
|
|
28
|
+
their annotations from it:
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from postyp import Array, Float64, Shape
|
|
32
|
+
|
|
33
|
+
def det3(m: Array[Float64, Shape[3, 3]]) -> Float64: ...
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The reference compiler is distributed separately as
|
|
37
|
+
[`post-py`](https://pypi.org/project/post-py/) (import name
|
|
38
|
+
`post_py`), which depends on this package. Development happens in
|
|
39
|
+
[openteams-ai/postpython](https://github.com/openteams-ai/postpython).
|
postyp-0.2.0/README.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# postyp
|
|
2
|
+
|
|
3
|
+
The [POST Python](https://post-py.org/) type vocabulary: scalar dtypes
|
|
4
|
+
(`Float64`, `Int64`, `Bool`, …), `Array` with `Shape` and layout
|
|
5
|
+
qualifiers, and `DataFrame`/`Series` annotations.
|
|
6
|
+
|
|
7
|
+
`postyp` is the canonical, compiler-independent source of POST Python
|
|
8
|
+
type metadata (spec §10). Conforming compilers introspect this module
|
|
9
|
+
rather than duplicating dtype definitions; POST source files import
|
|
10
|
+
their annotations from it:
|
|
11
|
+
|
|
12
|
+
```python
|
|
13
|
+
from postyp import Array, Float64, Shape
|
|
14
|
+
|
|
15
|
+
def det3(m: Array[Float64, Shape[3, 3]]) -> Float64: ...
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
The reference compiler is distributed separately as
|
|
19
|
+
[`post-py`](https://pypi.org/project/post-py/) (import name
|
|
20
|
+
`post_py`), which depends on this package. Development happens in
|
|
21
|
+
[openteams-ai/postpython](https://github.com/openteams-ai/postpython).
|
postyp-0.2.0/postyp.py
ADDED
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
"""postyp — POST Python type library.
|
|
2
|
+
|
|
3
|
+
Defines the scalar, array, and dataframe types that form the type
|
|
4
|
+
vocabulary of POST Python source files. Import from here in any POST
|
|
5
|
+
Python module:
|
|
6
|
+
|
|
7
|
+
from postyp import Float64, Array, DataFrame, Shape
|
|
8
|
+
|
|
9
|
+
Design notes
|
|
10
|
+
------------
|
|
11
|
+
* Scalar dtypes mirror the array-api standard (data-apis.org) so that
|
|
12
|
+
POST Python's numeric tower is compatible with NumPy, CuPy, JAX, etc.
|
|
13
|
+
* Array[DType] / Array[DType, Shape(...)] is the compile-time array type.
|
|
14
|
+
Layout qualifiers such as COrder, FOrder, and Strides describe native
|
|
15
|
+
memory layouts for compiled code.
|
|
16
|
+
* DataFrame / LazyFrame / Series describe a typed logical dataframe model.
|
|
17
|
+
Interpreted compatibility mode can bridge to narwhals-compatible backends;
|
|
18
|
+
compiled mode is intended to lower to a native columnar runtime.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import sys
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
from typing import Any, ClassVar, Generic, Optional, Tuple, TypeVar, Union
|
|
26
|
+
|
|
27
|
+
# ---------------------------------------------------------------------------
|
|
28
|
+
# Sentinel for "no value" at the type level
|
|
29
|
+
# ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
_MISSING = object()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# ---------------------------------------------------------------------------
|
|
35
|
+
# Dtype base and scalar dtype hierarchy
|
|
36
|
+
# (mirrors array-api standard: https://data-apis.org/array-api/latest/API_specification/data_types.html)
|
|
37
|
+
# ---------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
class DType:
|
|
40
|
+
"""Abstract base for all POST Python dtypes.
|
|
41
|
+
|
|
42
|
+
Subclasses represent concrete scalar types. They are never
|
|
43
|
+
instantiated — they are used as type parameters only.
|
|
44
|
+
"""
|
|
45
|
+
# Compiler-facing metadata
|
|
46
|
+
itemsize: ClassVar[int] # bytes per element
|
|
47
|
+
signed: ClassVar[bool] # meaningful for integer types
|
|
48
|
+
kind: ClassVar[str] # 'i' int, 'u' uint, 'f' float, 'c' complex, 'b' bool, 's' str
|
|
49
|
+
|
|
50
|
+
def __class_getitem__(cls, item: Any) -> Any:
|
|
51
|
+
# Allow DType[...] syntax for future extensions
|
|
52
|
+
return cls
|
|
53
|
+
|
|
54
|
+
def __init_subclass__(cls, itemsize: int = 0, kind: str = "", signed: bool = True, **kw: Any) -> None:
|
|
55
|
+
super().__init_subclass__(**kw)
|
|
56
|
+
cls.itemsize = itemsize
|
|
57
|
+
cls.kind = kind
|
|
58
|
+
cls.signed = signed
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# -- Boolean -----------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
class Bool(DType, itemsize=1, kind='b', signed=False):
|
|
64
|
+
"""Boolean (True / False), 1 byte."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# -- Signed integers ---------------------------------------------------------
|
|
68
|
+
|
|
69
|
+
class Int8(DType, itemsize=1, kind='i', signed=True):
|
|
70
|
+
"""Signed 8-bit integer [-128, 127]."""
|
|
71
|
+
|
|
72
|
+
class Int16(DType, itemsize=2, kind='i', signed=True):
|
|
73
|
+
"""Signed 16-bit integer [-32 768, 32 767]."""
|
|
74
|
+
|
|
75
|
+
class Int32(DType, itemsize=4, kind='i', signed=True):
|
|
76
|
+
"""Signed 32-bit integer [-2³¹, 2³¹-1]."""
|
|
77
|
+
|
|
78
|
+
class Int64(DType, itemsize=8, kind='i', signed=True):
|
|
79
|
+
"""Signed 64-bit integer [-2⁶³, 2⁶³-1]."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# -- Unsigned integers -------------------------------------------------------
|
|
83
|
+
|
|
84
|
+
class UInt8(DType, itemsize=1, kind='u', signed=False):
|
|
85
|
+
"""Unsigned 8-bit integer [0, 255]."""
|
|
86
|
+
|
|
87
|
+
class UInt16(DType, itemsize=2, kind='u', signed=False):
|
|
88
|
+
"""Unsigned 16-bit integer [0, 65 535]."""
|
|
89
|
+
|
|
90
|
+
class UInt32(DType, itemsize=4, kind='u', signed=False):
|
|
91
|
+
"""Unsigned 32-bit integer [0, 2³²-1]."""
|
|
92
|
+
|
|
93
|
+
class UInt64(DType, itemsize=8, kind='u', signed=False):
|
|
94
|
+
"""Unsigned 64-bit integer [0, 2⁶⁴-1]."""
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# -- Floating point ----------------------------------------------------------
|
|
98
|
+
|
|
99
|
+
class Float16(DType, itemsize=2, kind='f', signed=True):
|
|
100
|
+
"""IEEE 754 half-precision float (binary16)."""
|
|
101
|
+
|
|
102
|
+
class Float32(DType, itemsize=4, kind='f', signed=True):
|
|
103
|
+
"""IEEE 754 single-precision float (binary32)."""
|
|
104
|
+
|
|
105
|
+
class Float64(DType, itemsize=8, kind='f', signed=True):
|
|
106
|
+
"""IEEE 754 double-precision float (binary64)."""
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# -- Complex -----------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
class Complex64(DType, itemsize=8, kind='c', signed=True):
|
|
112
|
+
"""Complex number: two Float32 components (real, imag)."""
|
|
113
|
+
|
|
114
|
+
class Complex128(DType, itemsize=16, kind='c', signed=True):
|
|
115
|
+
"""Complex number: two Float64 components (real, imag)."""
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# -- Text / bytes ------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
class Str(DType, itemsize=0, kind='s', signed=False):
|
|
121
|
+
"""Variable-length UTF-8 string.
|
|
122
|
+
|
|
123
|
+
Note: in compiled POST Python, string values are immutable and
|
|
124
|
+
passed by reference. itemsize=0 signals variable-width.
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
class Bytes(DType, itemsize=0, kind='s', signed=False):
|
|
128
|
+
"""Variable-length byte sequence."""
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# ---------------------------------------------------------------------------
|
|
132
|
+
# Convenience aliases — preferred defaults
|
|
133
|
+
# ---------------------------------------------------------------------------
|
|
134
|
+
|
|
135
|
+
#: Default integer type (64-bit signed, matches Python int semantics).
|
|
136
|
+
Int = Int64
|
|
137
|
+
|
|
138
|
+
#: Default floating-point type.
|
|
139
|
+
Float = Float64
|
|
140
|
+
|
|
141
|
+
#: Default complex type.
|
|
142
|
+
Complex = Complex128
|
|
143
|
+
|
|
144
|
+
#: Default boolean alias (mirrors Python's bool).
|
|
145
|
+
# Bool is already defined above.
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# ---------------------------------------------------------------------------
|
|
149
|
+
# All public dtype names (for introspection / checker use)
|
|
150
|
+
# ---------------------------------------------------------------------------
|
|
151
|
+
|
|
152
|
+
SCALAR_DTYPES: tuple[type[DType], ...] = (
|
|
153
|
+
Bool,
|
|
154
|
+
Int8, Int16, Int32, Int64,
|
|
155
|
+
UInt8, UInt16, UInt32, UInt64,
|
|
156
|
+
Float16, Float32, Float64,
|
|
157
|
+
Complex64, Complex128,
|
|
158
|
+
Str, Bytes,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
# ---------------------------------------------------------------------------
|
|
163
|
+
# Shape type
|
|
164
|
+
# ---------------------------------------------------------------------------
|
|
165
|
+
|
|
166
|
+
class Shape:
|
|
167
|
+
"""Compile-time shape descriptor for Array.
|
|
168
|
+
|
|
169
|
+
Examples::
|
|
170
|
+
|
|
171
|
+
Array[Float64, Shape[10]] # 1-D, length 10
|
|
172
|
+
Array[Float64, Shape[3, 3]] # 2-D, 3×3
|
|
173
|
+
Array[Float64, Shape[None, 128]] # 2-D, dynamic first dim
|
|
174
|
+
Array[Float64, Shape[...]] # any rank / any shape
|
|
175
|
+
|
|
176
|
+
None in a dimension means "dynamic size" (not known at compile time).
|
|
177
|
+
Ellipsis (...) means fully dynamic rank.
|
|
178
|
+
"""
|
|
179
|
+
|
|
180
|
+
dims: tuple[int | None, ...]
|
|
181
|
+
|
|
182
|
+
def __init__(self, *dims: int | None) -> None:
|
|
183
|
+
self.dims = dims
|
|
184
|
+
|
|
185
|
+
def __class_getitem__(cls, item: Any) -> "Shape":
|
|
186
|
+
if item is Ellipsis:
|
|
187
|
+
return cls() # fully dynamic
|
|
188
|
+
if isinstance(item, tuple):
|
|
189
|
+
return cls(*item)
|
|
190
|
+
return cls(item)
|
|
191
|
+
|
|
192
|
+
@property
|
|
193
|
+
def ndim(self) -> int | None:
|
|
194
|
+
"""Number of dimensions, or None if fully dynamic."""
|
|
195
|
+
return len(self.dims) if self.dims else None
|
|
196
|
+
|
|
197
|
+
def __repr__(self) -> str:
|
|
198
|
+
if not self.dims:
|
|
199
|
+
return "Shape[...]"
|
|
200
|
+
return f"Shape[{', '.join('?' if d is None else str(d) for d in self.dims)}]"
|
|
201
|
+
|
|
202
|
+
def __eq__(self, other: object) -> bool:
|
|
203
|
+
return isinstance(other, Shape) and self.dims == other.dims
|
|
204
|
+
|
|
205
|
+
def __hash__(self) -> int:
|
|
206
|
+
return hash(self.dims)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
#: Fully-dynamic shape sentinel — use when rank and sizes are unknown.
|
|
210
|
+
AnyShape = Shape()
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
# ---------------------------------------------------------------------------
|
|
214
|
+
# Array layout types
|
|
215
|
+
# ---------------------------------------------------------------------------
|
|
216
|
+
|
|
217
|
+
class ArrayLayout:
|
|
218
|
+
"""Base class for POST Python array layout descriptors."""
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@dataclass(frozen=True)
|
|
222
|
+
class _ContiguousOrder(ArrayLayout):
|
|
223
|
+
"""A C- or Fortran-contiguous array layout."""
|
|
224
|
+
|
|
225
|
+
order: str
|
|
226
|
+
|
|
227
|
+
def __repr__(self) -> str:
|
|
228
|
+
return f"{self.order}Order"
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class Strides(ArrayLayout):
|
|
232
|
+
"""Compile-time stride descriptor for Array.
|
|
233
|
+
|
|
234
|
+
Strides are measured in bytes, following NumPy's convention. ``None``
|
|
235
|
+
means the stride is dynamic and must be supplied by runtime array metadata.
|
|
236
|
+
"""
|
|
237
|
+
|
|
238
|
+
strides: tuple[int | None, ...]
|
|
239
|
+
|
|
240
|
+
def __init__(self, *strides: int | None) -> None:
|
|
241
|
+
for stride in strides:
|
|
242
|
+
if stride is not None and not (
|
|
243
|
+
isinstance(stride, int) and not isinstance(stride, bool)
|
|
244
|
+
):
|
|
245
|
+
raise TypeError(
|
|
246
|
+
"Strides values must be integers or None, "
|
|
247
|
+
f"got {stride!r}"
|
|
248
|
+
)
|
|
249
|
+
self.strides = strides
|
|
250
|
+
|
|
251
|
+
def __class_getitem__(cls, item: Any) -> "Strides":
|
|
252
|
+
if isinstance(item, tuple):
|
|
253
|
+
return cls(*item)
|
|
254
|
+
return cls(item)
|
|
255
|
+
|
|
256
|
+
@property
|
|
257
|
+
def ndim(self) -> int:
|
|
258
|
+
return len(self.strides)
|
|
259
|
+
|
|
260
|
+
def __repr__(self) -> str:
|
|
261
|
+
return f"Strides[{', '.join('?' if s is None else str(s) for s in self.strides)}]"
|
|
262
|
+
|
|
263
|
+
def __eq__(self, other: object) -> bool:
|
|
264
|
+
return isinstance(other, Strides) and self.strides == other.strides
|
|
265
|
+
|
|
266
|
+
def __hash__(self) -> int:
|
|
267
|
+
return hash(self.strides)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
COrder = _ContiguousOrder("C")
|
|
271
|
+
FOrder = _ContiguousOrder("F")
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
# ---------------------------------------------------------------------------
|
|
275
|
+
# Array type
|
|
276
|
+
# ---------------------------------------------------------------------------
|
|
277
|
+
|
|
278
|
+
DT = TypeVar("DT", bound=DType)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
class Array(Generic[DT]):
|
|
282
|
+
"""POST Python array type (array-api compatible).
|
|
283
|
+
|
|
284
|
+
Use as a type annotation; never instantiate directly.
|
|
285
|
+
|
|
286
|
+
Examples::
|
|
287
|
+
|
|
288
|
+
def scale(a: Array[Float64], factor: Float64) -> Array[Float64]: ...
|
|
289
|
+
|
|
290
|
+
# With shape constraints:
|
|
291
|
+
def dot(a: Array[Float64, Shape[3]], b: Array[Float64, Shape[3]]) -> Float64: ...
|
|
292
|
+
|
|
293
|
+
The compiler maps Array[DType] to native memory layouts (e.g.
|
|
294
|
+
contiguous row-major buffers) and lowers operations to BLAS / SIMD
|
|
295
|
+
intrinsics as appropriate.
|
|
296
|
+
|
|
297
|
+
Runtime behaviour (when running under the standard interpreter) is
|
|
298
|
+
provided by the array-api-compat layer over whatever backend is active.
|
|
299
|
+
"""
|
|
300
|
+
|
|
301
|
+
dtype: ClassVar[type[DType]]
|
|
302
|
+
shape: ClassVar[Shape]
|
|
303
|
+
layout: ClassVar[ArrayLayout]
|
|
304
|
+
|
|
305
|
+
def __class_getitem__(cls, params: Any) -> type["Array[Any]"]:
|
|
306
|
+
if not isinstance(params, tuple):
|
|
307
|
+
params = (params,)
|
|
308
|
+
|
|
309
|
+
if len(params) == 1:
|
|
310
|
+
dtype_param, shape_param, layout_param = params[0], AnyShape, COrder
|
|
311
|
+
elif len(params) == 2:
|
|
312
|
+
dtype_param, second_param = params
|
|
313
|
+
if isinstance(second_param, Shape):
|
|
314
|
+
shape_param, layout_param = second_param, COrder
|
|
315
|
+
elif isinstance(second_param, ArrayLayout):
|
|
316
|
+
shape_param, layout_param = AnyShape, second_param
|
|
317
|
+
else:
|
|
318
|
+
raise TypeError(
|
|
319
|
+
"Array second parameter must be a Shape or ArrayLayout, "
|
|
320
|
+
f"got {type(second_param).__name__!r}"
|
|
321
|
+
)
|
|
322
|
+
elif len(params) == 3:
|
|
323
|
+
dtype_param, shape_param, layout_param = params
|
|
324
|
+
if not isinstance(shape_param, Shape):
|
|
325
|
+
raise TypeError(
|
|
326
|
+
f"Array second parameter must be a Shape, got {type(shape_param).__name__!r}"
|
|
327
|
+
)
|
|
328
|
+
if not isinstance(layout_param, ArrayLayout):
|
|
329
|
+
raise TypeError(
|
|
330
|
+
"Array third parameter must be an ArrayLayout, "
|
|
331
|
+
f"got {type(layout_param).__name__!r}"
|
|
332
|
+
)
|
|
333
|
+
if (
|
|
334
|
+
isinstance(layout_param, Strides)
|
|
335
|
+
and shape_param.ndim is not None
|
|
336
|
+
and layout_param.ndim != shape_param.ndim
|
|
337
|
+
):
|
|
338
|
+
raise TypeError(
|
|
339
|
+
"Array Strides rank must match Shape rank, "
|
|
340
|
+
f"got {layout_param.ndim} stride(s) for shape {shape_param!r}"
|
|
341
|
+
)
|
|
342
|
+
else:
|
|
343
|
+
raise TypeError(f"Array takes 1 to 3 type parameters, got {len(params)}")
|
|
344
|
+
|
|
345
|
+
if not (isinstance(dtype_param, type) and issubclass(dtype_param, DType)):
|
|
346
|
+
raise TypeError(
|
|
347
|
+
f"Array first parameter must be a DType subclass, got {dtype_param!r}"
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
ns = {
|
|
351
|
+
"dtype": dtype_param,
|
|
352
|
+
"shape": shape_param,
|
|
353
|
+
"layout": layout_param,
|
|
354
|
+
"__orig_class__": cls,
|
|
355
|
+
}
|
|
356
|
+
shape_name = "," + repr(shape_param) if shape_param is not AnyShape else ""
|
|
357
|
+
layout_name = "" if layout_param == COrder else "," + repr(layout_param)
|
|
358
|
+
return type(
|
|
359
|
+
f"Array[{dtype_param.__name__}{shape_name}{layout_name}]",
|
|
360
|
+
(cls,),
|
|
361
|
+
ns,
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
# -- Convenience array aliases -----------------------------------------------
|
|
366
|
+
|
|
367
|
+
BoolArray = Array[Bool]
|
|
368
|
+
Int8Array = Array[Int8]
|
|
369
|
+
Int16Array = Array[Int16]
|
|
370
|
+
Int32Array = Array[Int32]
|
|
371
|
+
Int64Array = Array[Int64]
|
|
372
|
+
UInt8Array = Array[UInt8]
|
|
373
|
+
UInt16Array = Array[UInt16]
|
|
374
|
+
UInt32Array = Array[UInt32]
|
|
375
|
+
UInt64Array = Array[UInt64]
|
|
376
|
+
Float16Array = Array[Float16]
|
|
377
|
+
Float32Array = Array[Float32]
|
|
378
|
+
Float64Array = Array[Float64]
|
|
379
|
+
Complex64Array = Array[Complex64]
|
|
380
|
+
Complex128Array = Array[Complex128]
|
|
381
|
+
|
|
382
|
+
#: Most common aliases
|
|
383
|
+
IntArray = Int64Array
|
|
384
|
+
FloatArray = Float64Array
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
# ---------------------------------------------------------------------------
|
|
388
|
+
# DataFrame / Series types
|
|
389
|
+
# ---------------------------------------------------------------------------
|
|
390
|
+
|
|
391
|
+
try:
|
|
392
|
+
import narwhals as nw
|
|
393
|
+
_HAS_NARWHALS = True
|
|
394
|
+
except ModuleNotFoundError:
|
|
395
|
+
_HAS_NARWHALS = False
|
|
396
|
+
|
|
397
|
+
#: Schema is a mapping of column name → DType subclass.
|
|
398
|
+
Schema = dict[str, type[DType]]
|
|
399
|
+
|
|
400
|
+
_NARWHALS_TO_POSTYP: "dict[Any, type[DType]]"
|
|
401
|
+
_POSTYP_TO_NARWHALS: "dict[type[DType], Any]"
|
|
402
|
+
|
|
403
|
+
if _HAS_NARWHALS:
|
|
404
|
+
import narwhals as nw
|
|
405
|
+
|
|
406
|
+
_NARWHALS_TO_POSTYP = {
|
|
407
|
+
nw.Boolean: Bool,
|
|
408
|
+
nw.Int8: Int8,
|
|
409
|
+
nw.Int16: Int16,
|
|
410
|
+
nw.Int32: Int32,
|
|
411
|
+
nw.Int64: Int64,
|
|
412
|
+
nw.UInt8: UInt8,
|
|
413
|
+
nw.UInt16: UInt16,
|
|
414
|
+
nw.UInt32: UInt32,
|
|
415
|
+
nw.UInt64: UInt64,
|
|
416
|
+
nw.Float32: Float32,
|
|
417
|
+
nw.Float64: Float64,
|
|
418
|
+
nw.String: Str,
|
|
419
|
+
}
|
|
420
|
+
_POSTYP_TO_NARWHALS = {v: k for k, v in _NARWHALS_TO_POSTYP.items()}
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def narwhals_dtype_to_postyp(nw_dtype: Any) -> type[DType]:
|
|
424
|
+
"""Convert a narwhals dtype to the equivalent postyp DType."""
|
|
425
|
+
if not _HAS_NARWHALS:
|
|
426
|
+
raise ImportError("narwhals is not installed")
|
|
427
|
+
result = _NARWHALS_TO_POSTYP.get(type(nw_dtype))
|
|
428
|
+
if result is None:
|
|
429
|
+
raise TypeError(f"No postyp equivalent for narwhals dtype {nw_dtype!r}")
|
|
430
|
+
return result
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def postyp_dtype_to_narwhals(dtype: type[DType]) -> Any:
|
|
434
|
+
"""Convert a postyp DType to the equivalent narwhals dtype."""
|
|
435
|
+
if not _HAS_NARWHALS:
|
|
436
|
+
raise ImportError("narwhals is not installed")
|
|
437
|
+
result = _POSTYP_TO_NARWHALS.get(dtype)
|
|
438
|
+
if result is None:
|
|
439
|
+
raise TypeError(f"No narwhals equivalent for postyp dtype {dtype.__name__!r}")
|
|
440
|
+
return result
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
class DataFrame:
|
|
444
|
+
"""POST Python DataFrame type annotation.
|
|
445
|
+
|
|
446
|
+
Backend-agnostic logical dataframe type. Interpreted compatibility mode
|
|
447
|
+
can wrap narwhals dataframes; compiled mode lowers supported operations to
|
|
448
|
+
the POST DataFrame runtime.
|
|
449
|
+
|
|
450
|
+
Examples::
|
|
451
|
+
|
|
452
|
+
def process(df: DataFrame) -> DataFrame: ...
|
|
453
|
+
|
|
454
|
+
# With schema (column→dtype mapping):
|
|
455
|
+
MyFrame = DataFrame.with_schema({"x": Float64, "y": Float64, "label": Int32})
|
|
456
|
+
def cluster(df: MyFrame) -> MyFrame: ...
|
|
457
|
+
"""
|
|
458
|
+
|
|
459
|
+
schema: ClassVar[Optional[Schema]] = None
|
|
460
|
+
|
|
461
|
+
@classmethod
|
|
462
|
+
def with_schema(cls, schema: Schema) -> type["DataFrame"]:
|
|
463
|
+
"""Return a DataFrame subtype bound to a specific column schema."""
|
|
464
|
+
name = "DataFrame[" + ", ".join(f"{k}:{v.__name__}" for k, v in schema.items()) + "]"
|
|
465
|
+
return type(name, (cls,), {"schema": schema})
|
|
466
|
+
|
|
467
|
+
@classmethod
|
|
468
|
+
def from_narwhals(cls, nw_df: Any) -> "DataFrame":
|
|
469
|
+
"""Wrap a narwhals DataFrame for use in POST Python code."""
|
|
470
|
+
if not _HAS_NARWHALS:
|
|
471
|
+
raise ImportError("narwhals is not installed")
|
|
472
|
+
obj = cls.__new__(cls)
|
|
473
|
+
object.__setattr__(obj, "_nw_df", nw_df)
|
|
474
|
+
return obj
|
|
475
|
+
|
|
476
|
+
def to_narwhals(self) -> Any:
|
|
477
|
+
if not _HAS_NARWHALS:
|
|
478
|
+
raise ImportError("narwhals is not installed")
|
|
479
|
+
return object.__getattribute__(self, "_nw_df")
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
class LazyFrame:
|
|
483
|
+
"""POST Python LazyFrame type annotation (deferred computation).
|
|
484
|
+
|
|
485
|
+
Represents an optimizable logical dataframe plan.
|
|
486
|
+
"""
|
|
487
|
+
|
|
488
|
+
schema: ClassVar[Optional[Schema]] = None
|
|
489
|
+
|
|
490
|
+
@classmethod
|
|
491
|
+
def with_schema(cls, schema: Schema) -> type["LazyFrame"]:
|
|
492
|
+
name = "LazyFrame[" + ", ".join(f"{k}:{v.__name__}" for k, v in schema.items()) + "]"
|
|
493
|
+
return type(name, (cls,), {"schema": schema})
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
class Series:
|
|
497
|
+
"""POST Python Series type annotation — a single typed column.
|
|
498
|
+
|
|
499
|
+
Examples::
|
|
500
|
+
|
|
501
|
+
def normalize(s: Series[Float64]) -> Series[Float64]: ...
|
|
502
|
+
"""
|
|
503
|
+
|
|
504
|
+
dtype: ClassVar[Optional[type[DType]]] = None
|
|
505
|
+
|
|
506
|
+
def __class_getitem__(cls, dtype: type[DType]) -> type["Series"]:
|
|
507
|
+
if not (isinstance(dtype, type) and issubclass(dtype, DType)):
|
|
508
|
+
raise TypeError(f"Series parameter must be a DType, got {dtype!r}")
|
|
509
|
+
return type(f"Series[{dtype.__name__}]", (cls,), {"dtype": dtype})
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
# ---------------------------------------------------------------------------
|
|
513
|
+
# Public re-exports
|
|
514
|
+
# ---------------------------------------------------------------------------
|
|
515
|
+
|
|
516
|
+
__all__ = [
|
|
517
|
+
# DType base
|
|
518
|
+
"DType",
|
|
519
|
+
# Scalar dtypes
|
|
520
|
+
"Bool",
|
|
521
|
+
"Int8", "Int16", "Int32", "Int64",
|
|
522
|
+
"UInt8", "UInt16", "UInt32", "UInt64",
|
|
523
|
+
"Float16", "Float32", "Float64",
|
|
524
|
+
"Complex64", "Complex128",
|
|
525
|
+
"Str", "Bytes",
|
|
526
|
+
# Aliases
|
|
527
|
+
"Int", "Float", "Complex",
|
|
528
|
+
# All scalar dtypes
|
|
529
|
+
"SCALAR_DTYPES",
|
|
530
|
+
# Shape / layout
|
|
531
|
+
"Shape", "AnyShape",
|
|
532
|
+
"ArrayLayout", "COrder", "FOrder", "Strides",
|
|
533
|
+
# Array
|
|
534
|
+
"Array",
|
|
535
|
+
"BoolArray", "IntArray", "FloatArray",
|
|
536
|
+
"Int8Array", "Int16Array", "Int32Array", "Int64Array",
|
|
537
|
+
"UInt8Array", "UInt16Array", "UInt32Array", "UInt64Array",
|
|
538
|
+
"Float16Array", "Float32Array", "Float64Array",
|
|
539
|
+
"Complex64Array", "Complex128Array",
|
|
540
|
+
# DataFrame types
|
|
541
|
+
"Schema",
|
|
542
|
+
"DataFrame", "LazyFrame", "Series",
|
|
543
|
+
# Narwhals bridge
|
|
544
|
+
"narwhals_dtype_to_postyp",
|
|
545
|
+
"postyp_dtype_to_narwhals",
|
|
546
|
+
]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.18"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
# The POST Python type vocabulary as its own distribution. The spec (§10,
|
|
6
|
+
# §12) treats `postyp` as the canonical, compiler-independent source of
|
|
7
|
+
# type metadata: multiple conforming compilers introspect it rather than
|
|
8
|
+
# duplicating dtype definitions. The module source lives in this
|
|
9
|
+
# directory; the compiler repository's dev shim adds it to sys.path.
|
|
10
|
+
|
|
11
|
+
[project]
|
|
12
|
+
name = "postyp"
|
|
13
|
+
version = "0.2.0"
|
|
14
|
+
description = "POST Python type vocabulary: scalar dtypes, Array, Shape, layouts, DataFrame and Series annotations."
|
|
15
|
+
readme = "README.md"
|
|
16
|
+
requires-python = ">=3.10"
|
|
17
|
+
authors = [{ name = "Travis E. Oliphant" }]
|
|
18
|
+
keywords = ["types", "dtypes", "array-api", "post-python"]
|
|
19
|
+
classifiers = [
|
|
20
|
+
"Development Status :: 3 - Alpha",
|
|
21
|
+
"Intended Audience :: Developers",
|
|
22
|
+
"Intended Audience :: Science/Research",
|
|
23
|
+
"Programming Language :: Python :: 3",
|
|
24
|
+
"Topic :: Software Development :: Compilers",
|
|
25
|
+
"Topic :: Scientific/Engineering",
|
|
26
|
+
]
|
|
27
|
+
dependencies = []
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Repository = "https://github.com/openteams-ai/postpython"
|
|
31
|
+
Specification = "https://github.com/openteams-ai/postpython/blob/main/docs/spec.md"
|
|
32
|
+
Website = "https://post-py.org/"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel.force-include]
|
|
35
|
+
"postyp.py" = "postyp.py"
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.sdist]
|
|
38
|
+
include = ["postyp.py", "README.md", "pyproject.toml"]
|