Use AI writing an Schema DataClass for Python.
文章目录
Schemas DataClass
A lightweight, Python 2/3 compatible data validation library that brings powerful schema validation to Python classes with a clean decorator-based API. Schemas DataClass combines the simplicity of Python dataclasses with robust validation capabilities, making it ideal for data processing, API validation, and configuration management.
🚀 Why Choose Schemas DataClass?
- Seamless Python 2/3 Compatibility: Works flawlessly across Python 2.7+ and 3.4+
- Type-Safe Data Validation: Comprehensive validation for strings, numbers, lists, and nested objects
- Clean, Pythonic API: Use standard class syntax with decorator-based validation
- Customizable Error Messages: Internationalization-ready with template formatting
- Zero Dependencies: Pure Python implementation using only standard libraries
- Efficient Performance: Lightweight design with minimal overhead
- Recursive Validation Protection: Safely handles nested and circular references
📦 Installation
From PyPI (Recommended)
| |
From Source
| |
For Development
| |
🚀 Quick Start
Basic Usage
| |
Custom Error Messages
| |
📚 Documentation Index
- Installation and Usage - Getting started guide
- Core Features - Key capabilities and design principles
- Complete Examples - Practical usage scenarios
- API Reference - Detailed API documentation
- Validation Features - Comprehensive validation capabilities
- Testing - How to run tests
- Compatibility - Supported Python versions
- Performance - Efficiency characteristics
- Contributing - How to contribute to the project
- License - Licensing information
- Changelog - Version history and updates
Installation and Usage
Basic Usage Guide
| |
Core Features
🔧 Field Types Support
StringField: String validation
- Length constraints (
min_length,max_length) - Regular expression validation (
regex) - Enumeration validation (
choices) - Custom error messages with template formatting
- Length constraints (
NumberField: Numeric validation (int, float, long)
- Range validation (
minvalue,maxvalue) - Enumeration validation (
choices) - Type validation with automatic coercion
- Custom error messages with template formatting
- Range validation (
ListField: List validation
- Length constraints (
min_length,max_length) - Item type validation (
item_type) - Supports nested types including strings, numbers, and dataclass models
- Custom error messages with template formatting
- Length constraints (
🌍 Custom Error Messages
- Multi-language Ready: Supports internationalization with locale-aware messages
- Template Formatting: Use
{parameter}style formatting for dynamic messages - Complete Coverage: Customize error messages for all validation types
- Backward Compatible: Optional feature that doesn’t affect existing code
| |
🎯 Decorator Syntax
| |
🔍 Custom Validation Decorator
| |
🔧 Custom Get Methods
| |
🌐 Nested DataClass Support
| |
Complete Examples
📁 Example Files
The project provides rich examples in the examples/ directory:
- Basic Usage Example - Field types, basic dataclass functionality
- Custom Error Messages Example - Multi-language messages, template formatting
- Advanced Features Example - Custom validation, nested dataclasses, conditional validation
- Real World Examples - User management, e-commerce products, blog systems
🚀 Running Examples
| |
💡 Quick Example
User Management System
| |
API Reference
Important Change Notice: Starting from version 2.0, all fields are optional by default (
required=False). For required fields, explicitly setrequired=True.
Field Types
StringField
| |
NumberField
| |
ListField
| |
Decorators
@dataclass
| |
@validate
| |
Error Message Keys
Common Error Message Keys
required: Required field is emptyinvalid_type: Type mismatch
StringField Error Message Keys
min_length: Length below minimummax_length: Length above maximumregex: Regular expression mismatchchoices: Value not in enumeration options
NumberField Error Message Keys
minvalue: Value below minimummaxvalue: Value above maximumchoices: Value not in enumeration options
ListField Error Message Keys
min_length: List length below minimummax_length: List length above maximuminvalid_list_item: List item type mismatch
Validation Features
String Validation
- Length validation:
min_length,max_length - Regular expression validation:
regex - Enumeration validation:
choices - Custom error messages for all validation types
Number Validation
- Range validation:
minvalue,maxvalue - Enumeration validation:
choices - Type validation: automatic support for int, float, long (Python 2)
- Custom error messages for all validation types
List Validation
- Length validation:
min_length,max_length - Item type validation:
item_type - Supports nesting: strings, numbers, dataclass models
- Custom error messages for list item type errors
DataClass Field Support
- Support dataclass as field types
- Automatic instantiation and validation
- Re-creation of objects on reassignment
- Support nested
to_dict()conversion - Validation on reassignment
Custom Validation
- Use
@validate("field_name")decorator - Executed after basic validation
- Support multiple custom validation functions
Custom Error Messages Features
- Multi-language Support: Full support for Chinese, English, and other languages
- Template Formatting: Support
{parameter}style parameter replacement - Complete Coverage: Support custom error messages for all validation types
- Backward Compatibility: Doesn’t affect existing code, optional usage
- Robustness: Graceful degradation when formatting fails, returns original template
- Zero Performance Impact: Same performance as original version when not using custom messages
Supported Error Message Types
- Common:
required,invalid_type - StringField:
min_length,max_length,regex,choices - NumberField:
minvalue,maxvalue,choices - ListField:
min_length,max_length,invalid_list_item
Testing
Running Tests
| |
Test Structure
| |
Test Coverage
- 25+ test cases covering all functionality
- 100% test pass rate
- Backward compatibility verification
- Multi-language error message tests
- Complex scenario boundary testing
Compatibility
- Python 2.7+: Fully supported
- Python 3.4+: Fully supported
- PyPy: Supported
- Jython: Theoretically supported (untested)
Performance
- Zero Dependencies: Uses only Python standard library
- Lightweight: Core code under 1000 lines
- High Performance: Fast validation with low memory usage
- Extensible: Easy to add new field types and validation rules
Contributing
Contributions are welcome! Please follow these steps:
- Fork the project
- Create a feature branch (
git checkout -b feature/amazing-feature) - Add test cases
- Ensure all tests pass (
pytest) - Update relevant documentation
- Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Create a Pull Request
Development Environment Setup
| |
Code Guidelines
- Follow PEP 8 coding style
- Add appropriate docstrings
- Add test cases for new features
- Maintain Python 2/3 compatibility
