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 (
selfandclsparameters) - Multiple Type Support: Allow parameters to accept multiple types using tuples or Union types
- Custom Validators: Create reusable validators with specific type configurations
Installation
# Add to your project (currently not on PyPI)
# Copy the validation module to your project
Requirements
- Python 3.7+
- No external dependencies (uses only standard library)
Quick Start
Basic Usage with Type Hints
from your_module 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 your_module 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 your_module 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 elementsDict[K, V]- Validates dictionary keys and valuesTuple[T1, T2, ...]- Validates tuple elements by positionSet[T]- Validates set elementsUnion[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 your_module 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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file python_type-1.0.0.tar.gz.
File metadata
- Download URL: python_type-1.0.0.tar.gz
- Upload date:
- Size: 6.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
26035e2b8fba1740e8b6c9d7487aa65b9d679b2ee80cd03e7adfa5dff95ce065
|
|
| MD5 |
e59e38c94d7158db5ee6ef6c0ccd581d
|
|
| BLAKE2b-256 |
4138f3dba97133d9beda629f752684fefad1cfdd746faa6f273b9bef30d63535
|
File details
Details for the file python_type-1.0.0-py3-none-any.whl.
File metadata
- Download URL: python_type-1.0.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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6c88dcc9203a8760b4990be61685751ead1727233418f2bd4602cdbc40aa5d1d
|
|
| MD5 |
a9cc30895407b5f74471d19407358464
|
|
| BLAKE2b-256 |
6be212ef39dab6aed7e702c2ce5ef8beea1fec5ee53b04a33cdba61785bc1c46
|