or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

command-line.mddecorators.mdembedded-acceleration.mdindex.mdtype-system.md

type-system.mddocs/

0

# Type System

1

2

Comprehensive type system supporting Python's native types, NumPy arrays, and custom data structures with automatic type inference and manual type annotations.

3

4

## Capabilities

5

6

### Type Annotations

7

8

String-based type annotations for function parameters and return values, enabling precise type specification for transpilation.

9

10

```python { .api }

11

# Function with type annotations

12

def compute(x: 'float', y: 'int', data: 'float[:]') -> 'float':

13

"""Function with explicit type annotations."""

14

return x + y + sum(data)

15

16

# Alternative syntax using annotation strings

17

def process_matrix(matrix: 'float[:,:]', scalar: 'complex') -> 'complex[:,:]':

18

"""Process 2D matrix with complex scalar."""

19

return matrix * scalar

20

```

21

22

### Basic Type Annotations

23

24

Fundamental Python types supported by Pyccel's type system.

25

26

```python { .api }

27

# Primitive types

28

'int' # Integer type

29

'float' # Floating-point type

30

'complex' # Complex number type

31

'bool' # Boolean type

32

'str' # String type

33

34

# Container types

35

'list' # Python list

36

'tuple' # Python tuple

37

'dict' # Python dictionary

38

```

39

40

### Array Type Annotations

41

42

NumPy-style array type annotations with dimension and contiguity specifications.

43

44

```python { .api }

45

# Array types

46

'int[:]' # 1D integer array

47

'float[:]' # 1D float array

48

'complex[:]' # 1D complex array

49

'bool[:]' # 1D boolean array

50

51

# Multi-dimensional arrays

52

'float[:,:]' # 2D float array

53

'int[:,:,:]' # 3D integer array

54

'complex[:,:,:,:]' # 4D complex array

55

56

# Contiguous memory layout

57

'float[::1]' # 1D contiguous float array

58

'int[:,::1]' # 2D array, contiguous in last dimension

59

'float[::1,::1]' # 2D fully contiguous array

60

```

61

62

### NumPy Specific Types

63

64

Precise NumPy data types for platform-specific numeric types.

65

66

```python { .api }

67

# NumPy integer types

68

from pyccel.ast.numpytypes import (

69

NumpyInt8Type, # 8-bit signed integer

70

NumpyInt16Type, # 16-bit signed integer

71

NumpyInt32Type, # 32-bit signed integer

72

NumpyInt64Type, # 64-bit signed integer

73

)

74

75

# NumPy floating-point types

76

from pyccel.ast.numpytypes import (

77

NumpyFloat32Type, # 32-bit floating-point

78

NumpyFloat64Type, # 64-bit floating-point

79

)

80

81

# NumPy complex types

82

from pyccel.ast.numpytypes import (

83

NumpyComplex64Type, # 64-bit complex (32-bit real + 32-bit imag)

84

NumpyComplex128Type, # 128-bit complex (64-bit real + 64-bit imag)

85

)

86

87

# NumPy array type

88

from pyccel.ast.numpytypes import NumpyNDArrayType

89

```

90

91

### Core Type Classes

92

93

Base classes and primitive types from Pyccel's type system hierarchy.

94

95

```python { .api }

96

from pyccel.ast.datatypes import (

97

PyccelType, # Base type class

98

PrimitiveType, # Base for primitive types

99

FixedSizeType, # Types with known size

100

ContainerType, # Container type base

101

102

# Primitive types

103

PrimitiveIntegerType, # Integer primitive

104

PrimitiveFloatingPointType, # Float primitive

105

PrimitiveComplexType, # Complex primitive

106

PrimitiveBooleanType, # Boolean primitive

107

108

# Container types

109

StringType, # String type

110

HomogeneousListType, # Uniform element list

111

HomogeneousTupleType, # Uniform element tuple

112

DictType, # Dictionary type

113

114

# Advanced types

115

CustomDataType, # User-defined types

116

UnionType, # Union type support

117

GenericType, # Generic type support

118

)

119

```

120

121

### Type Annotation Classes

122

123

Classes for handling complex type annotations and function signatures.

124

125

```python { .api }

126

from pyccel.ast.type_annotations import (

127

VariableTypeAnnotation, # Variable type annotation

128

FunctionTypeAnnotation, # Function type annotation

129

UnionTypeAnnotation, # Union type annotation

130

typenames_to_dtypes, # Convert type names to data types

131

)

132

133

# Usage example

134

def create_typed_function():

135

# Create variable annotation

136

var_annot = VariableTypeAnnotation('float[:]')

137

138

# Create function annotation

139

func_annot = FunctionTypeAnnotation(

140

arg_types=['int', 'float'],

141

return_type='float'

142

)

143

```

144

145

### Typing Extensions

146

147

Support for Python's typing module constructs and generic programming.

148

149

```python { .api }

150

from pyccel.ast.typingext import (

151

TypingAny, # typing.Any implementation

152

TypingFinal, # typing.Final implementation

153

TypingTypeVar, # typing.TypeVar implementation

154

TypingOverload, # typing.overload implementation

155

)

156

157

# Usage with type variables

158

from typing import TypeVar

159

T = TypeVar('T')

160

161

def generic_function(data: T) -> T:

162

"""Generic function using TypeVar."""

163

return data

164

```

165

166

### Type Conversion Utilities

167

168

Functions for converting between type representations and handling type metadata.

169

170

```python { .api }

171

from pyccel.ast.type_annotations import typenames_to_dtypes

172

173

def convert_types(type_names):

174

"""Convert type name strings to data type objects."""

175

return typenames_to_dtypes(type_names)

176

177

# Example usage

178

type_dict = typenames_to_dtypes(['int', 'float', 'complex'])

179

```

180

181

## Usage Examples

182

183

### Function Type Annotations

184

185

```python

186

from pyccel import epyccel

187

188

# Simple typed function

189

def add_arrays(a: 'float[:]', b: 'float[:]') -> 'float[:]':

190

"""Add two 1D arrays element-wise."""

191

return a + b

192

193

# Complex type annotations

194

def process_data(

195

matrix: 'float[:,:]',

196

weights: 'float[:]',

197

threshold: 'float',

198

use_bias: 'bool'

199

) -> 'tuple[float[:], bool]':

200

"""Process matrix data with weights and threshold."""

201

result = matrix @ weights

202

if use_bias:

203

result = result + threshold

204

success = all(result > 0)

205

return result, success

206

207

# Accelerate with type information

208

add_fast = epyccel(add_arrays)

209

process_fast = epyccel(process_data)

210

```

211

212

### Type Inference

213

214

Pyccel can infer types automatically in many cases:

215

216

```python

217

def auto_typed_function(x, y):

218

"""Types inferred from usage context."""

219

# If called with floats, types are inferred as float

220

z = x * 2.0 + y

221

return z

222

223

# Types inferred at transpilation time

224

auto_fast = epyccel(auto_typed_function)

225

result = auto_fast(3.5, 4.2) # Infers float types

226

```

227

228

### Custom Type Context

229

230

Provide additional type context for complex scenarios:

231

232

```python

233

from pyccel import epyccel

234

import numpy as np

235

236

def complex_function(data):

237

"""Function requiring type context."""

238

result = np.zeros_like(data)

239

return result * 2

240

241

# Provide context for type inference

242

context = {'np': np, 'zeros_like': np.zeros_like}

243

complex_fast = epyccel(complex_function, context_dict=context)

244

```

245

246

### Array Memory Layout

247

248

Specify memory layout for performance optimization:

249

250

```python

251

def matrix_multiply(a: 'float[:,::1]', b: 'float[::1,:]') -> 'float[:,:]':

252

"""Matrix multiplication with specific memory layouts."""

253

# a is C-contiguous in last dimension

254

# b is C-contiguous in first dimension

255

return a @ b

256

257

def vector_operations(v: 'float[::1]') -> 'float[::1]':

258

"""Vector operations with contiguous memory."""

259

return v * v + 2 * v + 1

260

```

261

262

## Type System Integration

263

264

### With NumPy

265

266

```python

267

import numpy as np

268

from pyccel import epyccel

269

270

def numpy_integration(arr: 'float[:]', dtype_spec: 'str') -> 'float[:]':

271

"""Function integrating with NumPy types."""

272

if dtype_spec == 'float32':

273

return arr.astype(np.float32)

274

else:

275

return arr.astype(np.float64)

276

277

numpy_fast = epyccel(numpy_integration)

278

```

279

280

### With SymPy

281

282

```python

283

import sympy as sp

284

from pyccel import lambdify

285

286

# SymPy expression with typed arguments

287

x, y = sp.symbols('x y')

288

expr = sp.sin(x) * sp.cos(y) + x**2

289

290

# Convert with precise types

291

args = {x: 'float64', y: 'float64'}

292

fast_expr = lambdify(expr, args, result_type='float64')

293

```

294

295

## Type Validation

296

297

Pyccel performs type checking during transpilation:

298

299

```python

300

def type_checked_function(a: 'int', b: 'float') -> 'float':

301

"""Function with type validation."""

302

# This will validate that operations are type-compatible

303

return a + b # int + float -> float (valid)

304

# return a + "string" # Would cause type error

305

```

306

307

## Platform-Specific Types

308

309

```python

310

# Platform-specific integer types

311

def platform_specific(data: 'int64[:]', count: 'int32') -> 'int64':

312

"""Function using platform-specific types."""

313

return data[:count].sum()

314

315

# Precision-specific floating-point

316

def precision_math(x: 'float32', y: 'float64') -> 'float64':

317

"""Mixed precision computation."""

318

return x + y # Automatically promotes to float64

319

```