CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyccel

Python-to-Fortran/C transpiler for scientific high-performance computing that automatically converts Python code into optimized low-level code.

Pending
Overview
Eval results
Files

type-system.mddocs/

Type System

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

Capabilities

Type Annotations

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

# Function with type annotations
def compute(x: 'float', y: 'int', data: 'float[:]') -> 'float':
    """Function with explicit type annotations."""
    return x + y + sum(data)

# Alternative syntax using annotation strings
def process_matrix(matrix: 'float[:,:]', scalar: 'complex') -> 'complex[:,:]':
    """Process 2D matrix with complex scalar."""
    return matrix * scalar

Basic Type Annotations

Fundamental Python types supported by Pyccel's type system.

# Primitive types
'int'           # Integer type
'float'         # Floating-point type  
'complex'       # Complex number type
'bool'          # Boolean type
'str'           # String type

# Container types
'list'          # Python list
'tuple'         # Python tuple
'dict'          # Python dictionary

Array Type Annotations

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

# Array types
'int[:]'         # 1D integer array
'float[:]'       # 1D float array
'complex[:]'     # 1D complex array
'bool[:]'        # 1D boolean array

# Multi-dimensional arrays
'float[:,:]'     # 2D float array
'int[:,:,:]'     # 3D integer array
'complex[:,:,:,:]' # 4D complex array

# Contiguous memory layout
'float[::1]'     # 1D contiguous float array
'int[:,::1]'     # 2D array, contiguous in last dimension
'float[::1,::1]' # 2D fully contiguous array

NumPy Specific Types

Precise NumPy data types for platform-specific numeric types.

# NumPy integer types
from pyccel.ast.numpytypes import (
    NumpyInt8Type,      # 8-bit signed integer
    NumpyInt16Type,     # 16-bit signed integer  
    NumpyInt32Type,     # 32-bit signed integer
    NumpyInt64Type,     # 64-bit signed integer
)

# NumPy floating-point types
from pyccel.ast.numpytypes import (
    NumpyFloat32Type,   # 32-bit floating-point
    NumpyFloat64Type,   # 64-bit floating-point
)

# NumPy complex types
from pyccel.ast.numpytypes import (
    NumpyComplex64Type,  # 64-bit complex (32-bit real + 32-bit imag)
    NumpyComplex128Type, # 128-bit complex (64-bit real + 64-bit imag)
)

# NumPy array type
from pyccel.ast.numpytypes import NumpyNDArrayType

Core Type Classes

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

from pyccel.ast.datatypes import (
    PyccelType,                    # Base type class
    PrimitiveType,                 # Base for primitive types
    FixedSizeType,                 # Types with known size
    ContainerType,                 # Container type base
    
    # Primitive types
    PrimitiveIntegerType,          # Integer primitive
    PrimitiveFloatingPointType,    # Float primitive
    PrimitiveComplexType,          # Complex primitive
    PrimitiveBooleanType,          # Boolean primitive
    
    # Container types
    StringType,                    # String type
    HomogeneousListType,           # Uniform element list
    HomogeneousTupleType,          # Uniform element tuple
    DictType,                      # Dictionary type
    
    # Advanced types
    CustomDataType,                # User-defined types
    UnionType,                     # Union type support
    GenericType,                   # Generic type support
)

Type Annotation Classes

Classes for handling complex type annotations and function signatures.

from pyccel.ast.type_annotations import (
    VariableTypeAnnotation,        # Variable type annotation
    FunctionTypeAnnotation,        # Function type annotation
    UnionTypeAnnotation,           # Union type annotation
    typenames_to_dtypes,           # Convert type names to data types
)

# Usage example
def create_typed_function():
    # Create variable annotation
    var_annot = VariableTypeAnnotation('float[:]')
    
    # Create function annotation
    func_annot = FunctionTypeAnnotation(
        arg_types=['int', 'float'],
        return_type='float'
    )

Typing Extensions

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

from pyccel.ast.typingext import (
    TypingAny,         # typing.Any implementation
    TypingFinal,       # typing.Final implementation  
    TypingTypeVar,     # typing.TypeVar implementation
    TypingOverload,    # typing.overload implementation
)

# Usage with type variables
from typing import TypeVar
T = TypeVar('T')

def generic_function(data: T) -> T:
    """Generic function using TypeVar."""
    return data

Type Conversion Utilities

Functions for converting between type representations and handling type metadata.

from pyccel.ast.type_annotations import typenames_to_dtypes

def convert_types(type_names):
    """Convert type name strings to data type objects."""
    return typenames_to_dtypes(type_names)

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

Usage Examples

Function Type Annotations

from pyccel import epyccel

# Simple typed function
def add_arrays(a: 'float[:]', b: 'float[:]') -> 'float[:]':
    """Add two 1D arrays element-wise."""
    return a + b

# Complex type annotations
def process_data(
    matrix: 'float[:,:]',
    weights: 'float[:]', 
    threshold: 'float',
    use_bias: 'bool'
) -> 'tuple[float[:], bool]':
    """Process matrix data with weights and threshold."""
    result = matrix @ weights
    if use_bias:
        result = result + threshold
    success = all(result > 0)
    return result, success

# Accelerate with type information
add_fast = epyccel(add_arrays)
process_fast = epyccel(process_data)

Type Inference

Pyccel can infer types automatically in many cases:

def auto_typed_function(x, y):
    """Types inferred from usage context."""
    # If called with floats, types are inferred as float
    z = x * 2.0 + y
    return z

# Types inferred at transpilation time
auto_fast = epyccel(auto_typed_function)
result = auto_fast(3.5, 4.2)  # Infers float types

Custom Type Context

Provide additional type context for complex scenarios:

from pyccel import epyccel
import numpy as np

def complex_function(data):
    """Function requiring type context."""
    result = np.zeros_like(data)
    return result * 2

# Provide context for type inference
context = {'np': np, 'zeros_like': np.zeros_like}
complex_fast = epyccel(complex_function, context_dict=context)

Array Memory Layout

Specify memory layout for performance optimization:

def matrix_multiply(a: 'float[:,::1]', b: 'float[::1,:]') -> 'float[:,:]':
    """Matrix multiplication with specific memory layouts."""
    # a is C-contiguous in last dimension
    # b is C-contiguous in first dimension  
    return a @ b

def vector_operations(v: 'float[::1]') -> 'float[::1]':
    """Vector operations with contiguous memory."""
    return v * v + 2 * v + 1

Type System Integration

With NumPy

import numpy as np
from pyccel import epyccel

def numpy_integration(arr: 'float[:]', dtype_spec: 'str') -> 'float[:]':
    """Function integrating with NumPy types."""
    if dtype_spec == 'float32':
        return arr.astype(np.float32)
    else:
        return arr.astype(np.float64)

numpy_fast = epyccel(numpy_integration)

With SymPy

import sympy as sp
from pyccel import lambdify

# SymPy expression with typed arguments
x, y = sp.symbols('x y')
expr = sp.sin(x) * sp.cos(y) + x**2

# Convert with precise types
args = {x: 'float64', y: 'float64'}
fast_expr = lambdify(expr, args, result_type='float64')

Type Validation

Pyccel performs type checking during transpilation:

def type_checked_function(a: 'int', b: 'float') -> 'float':
    """Function with type validation."""
    # This will validate that operations are type-compatible
    return a + b  # int + float -> float (valid)
    # return a + "string"  # Would cause type error

Platform-Specific Types

# Platform-specific integer types
def platform_specific(data: 'int64[:]', count: 'int32') -> 'int64':
    """Function using platform-specific types."""
    return data[:count].sum()

# Precision-specific floating-point
def precision_math(x: 'float32', y: 'float64') -> 'float64':
    """Mixed precision computation."""
    return x + y  # Automatically promotes to float64

Install with Tessl CLI

npx tessl i tessl/pypi-pyccel

docs

command-line.md

decorators.md

embedded-acceleration.md

index.md

type-system.md

tile.json