or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

bundling-configuration.mdindex.mdpackaging-systems.mdpython-functions.mdpython-layers.md
tile.json

python-functions.mddocs/

Python Lambda Functions

Core functionality for deploying Python Lambda functions with automatic dependency bundling and cross-platform compatibility.

Capabilities

PythonFunction Class

The main construct for creating Python Lambda functions with advanced packaging capabilities.

/**
 * AWS Lambda function construct for Python runtimes
 * Extends aws-cdk-lib/aws-lambda.Function with Python-specific bundling
 */
class PythonFunction extends Function {
  /** Uniquely identifies this class for property injection */
  static readonly PROPERTY_INJECTION_ID: string;
  
  /**
   * Creates a new Python Lambda function
   * @param scope - Construct scope
   * @param id - Construct identifier
   * @param props - Python function configuration properties
   */
  constructor(scope: Construct, id: string, props: PythonFunctionProps);
}

PythonFunction Properties

Configuration interface for Python function deployment.

/**
 * Properties for a PythonFunction
 * Extends standard Lambda function options with Python-specific settings
 */
interface PythonFunctionProps extends FunctionOptions {
  /**
   * Path to the source of the function or the location for dependencies
   * Must be an absolute or relative path to a directory containing Python code
   */
  readonly entry: string;

  /**
   * The runtime environment
   * Only runtimes of the Python family are supported
   */
  readonly runtime: Runtime;

  /**
   * The path (relative to entry) to the index file containing the exported handler
   * Must be a .py file
   * @default 'index.py'
   */
  readonly index?: string;

  /**
   * The name of the exported handler in the index file
   * @default 'handler'
   */
  readonly handler?: string;

  /**
   * Bundling options for custom Docker images, dependency management, and build configuration
   * @default - Use default bundling with auto-detected dependency management
   */
  readonly bundling?: BundlingOptions;
}

Usage Examples

Basic Python Function

import * as python from '@aws-cdk/aws-lambda-python-alpha';
import { Runtime } from 'aws-cdk-lib/aws-lambda';

const func = new python.PythonFunction(this, 'MyFunction', {
  entry: './lambda',  // Directory containing your Python code
  runtime: Runtime.PYTHON_3_8,
});

Function with Custom Handler

const func = new python.PythonFunction(this, 'CustomHandler', {
  entry: './src/lambda',
  runtime: Runtime.PYTHON_3_9,
  index: 'main.py',           // File containing the handler
  handler: 'process_event',   // Function name in main.py
});

Function with Requirements.txt

Directory structure:

lambda/
├── index.py          # Contains 'handler' function
├── requirements.txt  # pip dependencies
└── utils.py         # Additional modules
const func = new python.PythonFunction(this, 'WithDependencies', {
  entry: './lambda',
  runtime: Runtime.PYTHON_3_8,
  // Dependencies from requirements.txt are automatically installed
});

Function with Poetry

Directory structure:

lambda/
├── index.py
├── pyproject.toml    # Poetry project file
└── poetry.lock      # Poetry lock file
const func = new python.PythonFunction(this, 'PoetryFunction', {
  entry: './lambda',
  runtime: Runtime.PYTHON_3_9,
  bundling: {
    poetryIncludeHashes: true,  // Include dependency hashes
    poetryWithoutUrls: false,   // Include source URLs
  },
});

Function with Pipenv

Directory structure:

lambda/
├── index.py
├── Pipfile          # Pipenv dependencies
└── Pipfile.lock     # Pipenv lock file
const func = new python.PythonFunction(this, 'PipenvFunction', {
  entry: './lambda',
  runtime: Runtime.PYTHON_3_8,
  // Pipenv dependencies are automatically detected and installed
});

Function with uv

Directory structure:

lambda/
├── index.py
├── pyproject.toml   # uv project file
└── uv.lock         # uv lock file
const func = new python.PythonFunction(this, 'UvFunction', {
  entry: './lambda',
  runtime: Runtime.PYTHON_3_9,
  // uv dependencies are automatically detected and installed
});

Function with Asset Exclusions

const func = new python.PythonFunction(this, 'ExcludeFiles', {
  entry: './lambda',
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    assetExcludes: [
      '*.pyc',        // Compiled Python files
      '__pycache__',  // Python cache directories
      '.git',         // Git directory
      '.venv',        // Virtual environment
      'tests/',       // Test files
    ],
  },
});

Function with Custom Docker Image

import { DockerImage } from 'aws-cdk-lib/core';

const customImage = DockerImage.fromBuild('./docker');

const func = new python.PythonFunction(this, 'CustomImage', {
  entry: './lambda',
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    image: customImage,
    buildArgs: {
      PIP_INDEX_URL: 'https://pypi.org/simple/',
    },
  },
});

Function with Command Hooks

const func = new python.PythonFunction(this, 'WithHooks', {
  entry: './lambda',
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    commandHooks: {
      beforeBundling(inputDir: string, outputDir: string): string[] {
        return [
          'pip install --upgrade pip',  // Upgrade pip
          'pytest',                     // Run tests
        ];
      },
      afterBundling(inputDir: string, outputDir: string): string[] {
        return [
          'find . -name "*.pyc" -delete',  # Clean up compiled files
          'pip list',                      # List installed packages
        ];
      },
    },
  },
});

Function with ARM Architecture

import { Architecture } from 'aws-cdk-lib/aws-lambda';

const func = new python.PythonFunction(this, 'ArmFunction', {
  entry: './lambda',
  runtime: Runtime.PYTHON_3_9,
  architecture: Architecture.ARM_64,  // ARM architecture support
});

Runtime Validation

The PythonFunction construct automatically validates that only Python runtimes are used:

// ✅ Valid - Python runtime
new python.PythonFunction(this, 'Valid', {
  entry: './lambda',
  runtime: Runtime.PYTHON_3_8,
});

// ❌ Invalid - Will throw error
new python.PythonFunction(this, 'Invalid', {
  entry: './lambda',
  runtime: Runtime.NODEJS_18_X,  // Error: Only PYTHON runtimes are supported
});

Error Handling

Common errors and their solutions:

  • "Cannot find index file": The specified index file doesn't exist in the entry directory
  • "Only Python (.py) index files are supported": Index file must have .py extension
  • "Only PYTHON runtimes are supported": Runtime must be from the Python family
  • Docker not available: Docker is required for bundling dependencies

Performance Considerations

  • Use lockfiles (poetry.lock, Pipfile.lock, uv.lock) for consistent builds
  • Consider using layers for shared dependencies across multiple functions
  • Asset hash is calculated from source files - use .dockerignore to exclude unnecessary files
  • Dependencies are cached in Docker containers for faster subsequent builds