Skip to main content

A powerful and flexible Python decorator library for runtime type validation using type hints and custom type specifications.

Project description

TypedPython

A powerful and flexible Python decorator library for runtime type validation using type hints and custom type specifications.

Features

  • Automatic Type Validation: Leverages Python type hints for seamless parameter validation
  • Custom Type Overrides: Override specific parameter types without modifying function signatures
  • Complex Type Support: Validates generic types like List[int], Dict[str, int], Union[int, str], etc.
  • Flexible Modes: Choose between strict validation (all parameters) or selective validation
  • Return Type Validation: Validate function return types with a separate decorator
  • Detailed Error Messages: Clear, formatted error messages with file location and parameter details
  • Class Method Support: Works with both functions and class methods (self and cls parameters)
  • Multiple Type Support: Allow parameters to accept multiple types using tuples or Union types
  • Custom Validators: Create reusable validators with specific type configurations

Installation

pip install python-type==1.0.0

Requirements

  • Python 3.7+
  • No external dependencies (uses only standard library)

Quick Start

Basic Usage with Type Hints

from python_type import validate_data

@validate_data()
def greet(name: str, age: int, active: bool = True) -> str:
    return f"Hello {name}, you are {age} years old"

# This will work
greet("John", 25)

# This will raise ValidationError
greet(123, "twenty")  # Wrong types

Custom Type Overrides

@validate_data(age=(int, str))  # Allow both int and str for age
def process_age(name: str, age: int) -> str:
    return f"{name} is {age} years old"

# Both of these work
process_age("Alice", 30)     # int
process_age("Bob", "25")     # str

Complex Type Validation

from typing import List, Dict, Union

@validate_data()
def process_data(
    users: List[str], 
    config: Dict[str, int], 
    status: Union[str, int] = "active"
) -> bool:
    return len(users) > 0

# Valid calls
process_data(["user1", "user2"], {"setting": 1})
process_data(["user1"], {"setting": 1}, "inactive")
process_data(["user1"], {"setting": 1}, 404)

Selective Validation (Non-Strict Mode)

@validate_data(strict=False, age=int)  # Only validate 'age' parameter
def flexible_function(name, age, other_param):
    return f"{name} is {age} years old"

# Only 'age' is validated, other parameters can be any type
flexible_function("John", 25, ["any", "type", "here"])

Return Type Validation

from python_type import validate_return_type

@validate_return_type
def calculate_sum(a: int, b: int) -> int:
    return a + b  # Must return an int

@validate_return_type
def get_user_data(user_id: int) -> Dict[str, str]:
    return {"name": "John", "email": "john@example.com"}

Custom Validators

from python_type import create_validator

# Create a reusable validator
user_validator = create_validator({
    'email': str,
    'age': int,
    'active': bool
})

@user_validator
def process_user(email, age, active):
    return f"User {email} is {age} years old and {'active' if active else 'inactive'}"

Advanced Features

Supported Generic Types

  • List[T] - Validates list elements
  • Dict[K, V] - Validates dictionary keys and values
  • Tuple[T1, T2, ...] - Validates tuple elements by position
  • Set[T] - Validates set elements
  • Union[T1, T2, ...] - Allows multiple types
  • Custom generic types that follow typing conventions

Class Method Support

class UserManager:
    @validate_data()
    def create_user(self, name: str, age: int) -> str:
        return f"Created user {name}, age {age}"
    
    @validate_data()
    @classmethod
    def from_config(cls, config: Dict[str, str]) -> 'UserManager':
        return cls()

Error Messages

The library provides detailed, formatted error messages that include:

======================================================================
TYPE VALIDATION ERROR
======================================================================
📁 File: /path/to/your/file.py
📍 Line: 42
🔧 Function: my_function()
❌ Errors found: 1
======================================================================

💥 ERROR 1:
   Parameter: 'age' (position 2)
   ✅ Expected: int (from type hint)
   ❌ Received: str
   📦 Value: str('twenty')
======================================================================

Override Parameter Validation

The decorator validates that all override parameters exist in the function:

# This will raise a configuration error
@validate_data(non_existent_param=int)
def my_function(name: str, age: int):
    pass

Exception Handling

The library raises ValidationError (a subclass of ValueError) when validation fails:

from python_type import ValidationError

try:
    my_function("wrong", "types")
except ValidationError as e:
    print(e)  # Detailed error message with emojis and formatting

API Reference

validate_data(*, strict: bool = True, **types_override)

Main decorator for parameter validation.

Parameters:

  • strict (bool): If True, validates all parameters with type hints. If False, only validates parameters with overrides.
  • **types_override: Keyword arguments to override specific parameter types.

Returns:

  • Configured decorator function

validate_return_type(func)

Decorator to validate function return types based on type hints.

Parameters:

  • func: Function to decorate

Returns:

  • Wrapped function with return type validation

create_validator(custom_types: Dict[str, Any])

Creates a custom validator with specific types.

Parameters:

  • custom_types: Dictionary mapping parameter names to expected types

Returns:

  • Configured decorator function

ValidationError

Custom exception class for type validation errors. Inherits from ValueError.

Use Cases

  • API Development: Validate request parameters automatically
  • Data Processing: Ensure data types are correct before processing
  • Function Contracts: Enforce type contracts in critical functions
  • Debugging: Catch type-related bugs early in development
  • Testing: Validate that functions receive expected types

Why TypedPython?

  • Zero Runtime Overhead: Only validates when decorators are applied
  • Non-Intrusive: Works with existing code without modification
  • Flexible: Choose between automatic type hint validation or manual specification
  • Production Ready: Comprehensive error handling and edge case coverage
  • Developer Friendly: Clear error messages with emojis help debug issues quickly
  • Comprehensive: Supports complex generic types, class methods, and custom validators

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python_type-1.1.0.tar.gz (6.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

python_type-1.1.0-py3-none-any.whl (7.1 kB view details)

Uploaded Python 3

File details

Details for the file python_type-1.1.0.tar.gz.

File metadata

  • Download URL: python_type-1.1.0.tar.gz
  • Upload date:
  • Size: 6.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.5

File hashes

Hashes for python_type-1.1.0.tar.gz
Algorithm Hash digest
SHA256 d36b6681ec104047fabfcd1936d38ecf08dc2e77820491bae0e7e7b927588e90
MD5 d272cf5c82f0f50283849281f5767afd
BLAKE2b-256 16a49e269079d0fc375195374d24387c9bdd718c9c548075a7e8a229f305363e

See more details on using hashes here.

File details

Details for the file python_type-1.1.0-py3-none-any.whl.

File metadata

  • Download URL: python_type-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 7.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.5

File hashes

Hashes for python_type-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8e528dd62cf67d9c30055c58e948b05a79e0b8b8f7c4aac7636220f9590333b7
MD5 72437a43278941c12a3f8d5ab444d690
BLAKE2b-256 bc82987a5b3483d373f996686d01b8ba1f613435bfa8b0cbeec226eb9f9a8d18

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page