# Schemas DataClass
[](https://pypi.org/project/schemas-dataclass/)
[](LICENSE)
[](https://github.com/b40yd/schemas-python/actions/workflows/ci.yml)
[](https://coveralls.io/github/b40yd/schemas-python)
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)
```bash
pip install schemas-dataclass
```
### From Source
```bash
git clone https://github.com/schemas/dataclass.git
cd dataclass
python setup.py install
```
### For Development
```bash
git clone https://github.com/schemas/dataclass.git
cd dataclass
pip install -e .
pip install -r requirements-dev.txt
```
## 🚀 Quick Start
### Basic Usage
```python
from schema_dataclass import StringField, NumberField, dataclass, ValidationError
@dataclass
class User(object):
name = StringField(min_length=2, max_length=50)
age = NumberField(minvalue=0, maxvalue=120)
email = StringField(
regex=r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
)
# Create a user
user = User(name="Alice", age=25, email="alice@example.com")
print(user.to_dict()) # {'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}
```
### Custom Error Messages
```python
@dataclass
class User(object):
name = StringField(
min_length=2,
error_messages={
'required': 'Name is required',
'min_length': 'Name must be at least {min_length} characters long'
}
)
try:
user = User(name="A") # Too short
except ValidationError as e:
print(e.message) # Output: Name must be at least 2 characters long
```
## 📚 Documentation Index
- **[Installation and Usage](#installation-and-usage)** - Getting started guide
- **[Core Features](#core-features)** - Key capabilities and design principles
- **[Complete Examples](#complete-examples)** - Practical usage scenarios
- **[API Reference](#api-reference)** - Detailed API documentation
- **[Validation Features](#validation-features)** - Comprehensive validation capabilities
- **[Testing](#testing)** - How to run tests
- **[Compatibility](#compatibility)** - Supported Python versions
- **[Performance](#performance)** - Efficiency characteristics
- **[Contributing](#contributing)** - How to contribute to the project
- **[License](#license)** - Licensing information
- **[Changelog](#changelog)** - Version history and updates
## Installation and Usage
### Basic Usage Guide
```python
from schema_dataclass import StringField, NumberField, ListField, dataclass
@dataclass
class User(object):
name = StringField(min_length=2, max_length=50)
age = NumberField(minvalue=0, maxvalue=120)
email = StringField(
regex=r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
)
tags = ListField(item_type=str, required=False)
# Create and use
user = User(
name="Alice",
age=25,
email="alice@example.com",
tags=["developer", "python"]
)
print(user.name) # Alice
print(user['age']) # 25
print(user.get('email')) # alice@example.com
print(user.to_dict()) # Convert to dictionary
```
## 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
- **NumberField**: Numeric validation (int, float, long)
- Range validation (`minvalue`, `maxvalue`)
- Enumeration validation (`choices`)
- Type validation with automatic coercion
- Custom error messages with template formatting
- **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
### 🌍 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
```python
# Custom error messages example
@dataclass
class User(object):
name = StringField(
min_length=3,
max_length=20,
error_messages={
'required': 'Username is required',
'min_length': 'Username must be at least {min_length} characters long',
'max_length': 'Username cannot exceed {max_length} characters'
}
)
```
### 🎯 Decorator Syntax
```python
@dataclass
class User(object):
name = StringField(min_length=1, max_length=100)
age = NumberField(minvalue=0, maxvalue=150)
```
### 🔍 Custom Validation Decorator
```python
@dataclass
class Product(object):
name = StringField()
price = NumberField()
@validate("name")
def validate_name_custom(self, name):
if not name.isalnum():
raise ValidationError("Name must be alphanumeric")
@validate("price")
def validate_price_custom(self, price):
if price <= 0:
raise ValidationError("Price must be positive")
```
### 🔧 Custom Get Methods
```python
@dataclass
class BlogPost(object):
title = StringField()
status = StringField(default='draft')
def get_title(self):
"""Custom method to get formatted title"""
title = self.__dict__.get('title', '')
status = self.__dict__.get('status', 'draft')
return "[{0}] {1}".format(status.upper(), title)
```
### 🌐 Nested DataClass Support
```python
@dataclass
class Address(object):
street = StringField()
city = StringField()
zip_code = StringField()
@dataclass
class User(object):
name = StringField()
address = Address # Class reference (auto-instantiated)
addresses = ListField(item_type=Address) # List of nested objects
```
## Complete Examples
### 📁 Example Files
The project provides rich examples in the `examples/` directory:
- **[Basic Usage Example](examples/basic_usage.py)** - Field types, basic dataclass functionality
- **[Custom Error Messages Example](examples/custom_error_messages.py)** - Multi-language messages, template formatting
- **[Advanced Features Example](examples/advanced_features.py)** - Custom validation, nested dataclasses, conditional validation
- **[Real World Examples](examples/real_world_examples.py)** - User management, e-commerce products, blog systems
### 🚀 Running Examples
```bash
# Basic usage example
python examples/basic_usage.py
# Custom error messages example
python examples/custom_error_messages.py
# Advanced features example
python examples/advanced_features.py
# Real world examples
python examples/real_world_examples.py
```
### 💡 Quick Example
#### User Management System
```python
from schema_dataclass import StringField, NumberField, ListField, dataclass, validate
@dataclass
class User(object):
username = StringField(
min_length=3,
max_length=20,
regex=r'^[a-zA-Z][a-zA-Z0-9_]*$',
error_messages={
'required': 'Username is required',
'min_length': 'Username must be at least {min_length} characters long',
'regex': 'Username must start with a letter and contain only letters, numbers, and underscores'
}
)
email = StringField(
regex=r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
error_messages={
'required': 'Email address is required',
'regex': 'Please enter a valid email address'
}
)
age = NumberField(
minvalue=13,
maxvalue=120,
error_messages={
'minvalue': 'Age cannot be less than {minvalue}',
'maxvalue': 'Age cannot be greater than {maxvalue}'
}
)
tags = ListField(
item_type=str,
required=False,
max_length=10,
error_messages={
'max_length': 'Cannot have more than {max_length} tags'
}
)
@validate("username")
def validate_username_not_reserved(self, username):
"""Check if username is a reserved word"""
reserved = ['admin', 'root', 'system']
if username.lower() in reserved:
raise ValidationError(f"Username '{username}' is a reserved word")
# Usage example
user = User(
username="alice_dev",
email="alice@example.com",
age=28,
tags=["developer", "python"]
)
print("User: {}".format(user.username))
print("Email: {}".format(user.email))
print("Age: {}".format(user.age))
print("Tags: {}".format(user.tags))
```
## API Reference
> **Important Change Notice**: Starting from version 2.0, all fields are optional by default (`required=False`). For required fields, explicitly set `required=True`.
### Field Types
#### StringField
```python
StringField(
default=None, # Default value
alias=None, # Field alias
required=False, # Whether the field is required (default: False)
min_length=None, # Minimum length
max_length=None, # Maximum length
regex=None, # Regular expression pattern
choices=None, # Enumeration options
error_messages=None # Custom error messages
)
```
#### NumberField
```python
NumberField(
default=None, # Default value
alias=None, # Field alias
required=False, # Whether the field is required (default: False)
minvalue=None, # Minimum value
maxvalue=None, # Maximum value
choices=None, # Enumeration options
error_messages=None # Custom error messages
)
```
#### ListField
```python
ListField(
default=None, # Default value
alias=None, # Field alias
required=False, # Whether the field is required (default: False)
min_length=None, # Minimum length
max_length=None, # Maximum length
item_type=None, # Type of list items
error_messages=None # Custom error messages
)
```
### Decorators
#### @dataclass
```python
@dataclass
class MyClass(object):
field1 = StringField()
field2 = NumberField()
```
#### @validate
```python
@dataclass
class MyClass(object):
field1 = StringField()
@validate("field1")
def validate_field1(self, value):
# Custom validation logic
if not condition:
raise ValidationError("Custom validation failed")
```
### Error Message Keys
#### Common Error Message Keys
- `required`: Required field is empty
- `invalid_type`: Type mismatch
#### StringField Error Message Keys
- `min_length`: Length below minimum
- `max_length`: Length above maximum
- `regex`: Regular expression mismatch
- `choices`: Value not in enumeration options
#### NumberField Error Message Keys
- `minvalue`: Value below minimum
- `maxvalue`: Value above maximum
- `choices`: Value not in enumeration options
#### ListField Error Message Keys
- `min_length`: List length below minimum
- `max_length`: List length above maximum
- `invalid_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
```bash
# Run all tests
pytest
# Run specific test file
pytest tests/test_fields.py
# Run tests with coverage
pytest --cov=schema_dataclass
# Run tests with specific markers
pytest -m "unit"
pytest -m "integration"
pytest -m "error_messages"
```
### Test Structure
```
tests/
├── conftest.py # pytest configuration and fixtures
├── test_fields.py # Field type tests
├── test_custom_error_messages.py # Custom error messages tests
├── test_dataclass.py # dataclass functionality tests
└── test_integration.py # Integration tests
```
### 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:
1. Fork the project
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Add test cases
4. Ensure all tests pass (`pytest`)
5. Update relevant documentation
6. Commit your changes (`git commit -m 'Add amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Create a Pull Request
### Development Environment Setup
```bash
git clone https://github.com/schemas/dataclass.git
cd dataclass
pip install -e .
pip install -r requirements-dev.txt
```
### Code Guidelines
- Follow PEP 8 coding style
- Add appropriate docstrings
- Add test cases for new features
- Maintain Python 2/3 compatibility
## License
This project is licensed under the GNU General Public License v3.0. See the [LICENSE](LICENSE) file for details.
## Changelog
Check [CHANGELOG.md](CHANGELOG.md) for detailed version history and updates.
---
**Note**: This library is fully compatible with Python 2.7 and Python 3.x. Custom error messages are an optional feature that doesn't affect the usage of existing code.
Raw data
{
"_id": null,
"home_page": null,
"name": "schema-dataclass",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": "Schemas DataClass Team <bb.qnyd@gmail.com>",
"keywords": "dataclass, fields, python2, python3, schema, validation",
"author": null,
"author_email": "Schemas DataClass Team <bb.qnyd@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/63/51/04ce2a6f532d694a8b5810ef31c1709a866f753a97675318e6d7054ebcf6/schema_dataclass-0.0.2.tar.gz",
"platform": null,
"description": "# Schemas DataClass\n\n[](https://pypi.org/project/schemas-dataclass/)\n[](LICENSE)\n[](https://github.com/b40yd/schemas-python/actions/workflows/ci.yml)\n[](https://coveralls.io/github/b40yd/schemas-python)\n\nA 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.\n\n## \ud83d\ude80 Why Choose Schemas DataClass?\n\n- **Seamless Python 2/3 Compatibility**: Works flawlessly across Python 2.7+ and 3.4+\n- **Type-Safe Data Validation**: Comprehensive validation for strings, numbers, lists, and nested objects\n- **Clean, Pythonic API**: Use standard class syntax with decorator-based validation\n- **Customizable Error Messages**: Internationalization-ready with template formatting\n- **Zero Dependencies**: Pure Python implementation using only standard libraries\n- **Efficient Performance**: Lightweight design with minimal overhead\n- **Recursive Validation Protection**: Safely handles nested and circular references\n\n## \ud83d\udce6 Installation\n\n### From PyPI (Recommended)\n\n```bash\npip install schemas-dataclass\n```\n\n### From Source\n\n```bash\ngit clone https://github.com/schemas/dataclass.git\ncd dataclass\npython setup.py install\n```\n\n### For Development\n\n```bash\ngit clone https://github.com/schemas/dataclass.git\ncd dataclass\npip install -e .\npip install -r requirements-dev.txt\n```\n\n## \ud83d\ude80 Quick Start\n\n### Basic Usage\n\n```python\nfrom schema_dataclass import StringField, NumberField, dataclass, ValidationError\n\n@dataclass\nclass User(object):\n name = StringField(min_length=2, max_length=50)\n age = NumberField(minvalue=0, maxvalue=120)\n email = StringField(\n regex=r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'\n )\n\n# Create a user\nuser = User(name=\"Alice\", age=25, email=\"alice@example.com\")\nprint(user.to_dict()) # {'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}\n```\n\n### Custom Error Messages\n\n```python\n@dataclass\nclass User(object):\n name = StringField(\n min_length=2,\n error_messages={\n 'required': 'Name is required',\n 'min_length': 'Name must be at least {min_length} characters long'\n }\n )\n\ntry:\n user = User(name=\"A\") # Too short\nexcept ValidationError as e:\n print(e.message) # Output: Name must be at least 2 characters long\n```\n\n## \ud83d\udcda Documentation Index\n\n- **[Installation and Usage](#installation-and-usage)** - Getting started guide\n- **[Core Features](#core-features)** - Key capabilities and design principles\n- **[Complete Examples](#complete-examples)** - Practical usage scenarios\n- **[API Reference](#api-reference)** - Detailed API documentation\n- **[Validation Features](#validation-features)** - Comprehensive validation capabilities\n- **[Testing](#testing)** - How to run tests\n- **[Compatibility](#compatibility)** - Supported Python versions\n- **[Performance](#performance)** - Efficiency characteristics\n- **[Contributing](#contributing)** - How to contribute to the project\n- **[License](#license)** - Licensing information\n- **[Changelog](#changelog)** - Version history and updates\n\n## Installation and Usage\n\n### Basic Usage Guide\n\n```python\nfrom schema_dataclass import StringField, NumberField, ListField, dataclass\n\n@dataclass\nclass User(object):\n name = StringField(min_length=2, max_length=50)\n age = NumberField(minvalue=0, maxvalue=120)\n email = StringField(\n regex=r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'\n )\n tags = ListField(item_type=str, required=False)\n\n# Create and use\nuser = User(\n name=\"Alice\",\n age=25,\n email=\"alice@example.com\",\n tags=[\"developer\", \"python\"]\n)\n\nprint(user.name) # Alice\nprint(user['age']) # 25\nprint(user.get('email')) # alice@example.com\nprint(user.to_dict()) # Convert to dictionary\n```\n\n## Core Features\n\n### \ud83d\udd27 Field Types Support\n\n- **StringField**: String validation\n - Length constraints (`min_length`, `max_length`)\n - Regular expression validation (`regex`)\n - Enumeration validation (`choices`)\n - Custom error messages with template formatting\n \n- **NumberField**: Numeric validation (int, float, long)\n - Range validation (`minvalue`, `maxvalue`)\n - Enumeration validation (`choices`)\n - Type validation with automatic coercion\n - Custom error messages with template formatting\n \n- **ListField**: List validation\n - Length constraints (`min_length`, `max_length`)\n - Item type validation (`item_type`)\n - Supports nested types including strings, numbers, and dataclass models\n - Custom error messages with template formatting\n\n### \ud83c\udf0d Custom Error Messages\n\n- **Multi-language Ready**: Supports internationalization with locale-aware messages\n- **Template Formatting**: Use `{parameter}` style formatting for dynamic messages\n- **Complete Coverage**: Customize error messages for all validation types\n- **Backward Compatible**: Optional feature that doesn't affect existing code\n\n```python\n# Custom error messages example\n@dataclass\nclass User(object):\n name = StringField(\n min_length=3,\n max_length=20,\n error_messages={\n 'required': 'Username is required',\n 'min_length': 'Username must be at least {min_length} characters long',\n 'max_length': 'Username cannot exceed {max_length} characters'\n }\n )\n```\n\n### \ud83c\udfaf Decorator Syntax\n\n```python\n@dataclass\nclass User(object):\n name = StringField(min_length=1, max_length=100)\n age = NumberField(minvalue=0, maxvalue=150)\n```\n\n### \ud83d\udd0d Custom Validation Decorator\n\n```python\n@dataclass\nclass Product(object):\n name = StringField()\n price = NumberField()\n \n @validate(\"name\")\n def validate_name_custom(self, name):\n if not name.isalnum():\n raise ValidationError(\"Name must be alphanumeric\")\n \n @validate(\"price\")\n def validate_price_custom(self, price):\n if price <= 0:\n raise ValidationError(\"Price must be positive\")\n```\n\n### \ud83d\udd27 Custom Get Methods\n\n```python\n@dataclass\nclass BlogPost(object):\n title = StringField()\n status = StringField(default='draft')\n \n def get_title(self):\n \"\"\"Custom method to get formatted title\"\"\"\n title = self.__dict__.get('title', '')\n status = self.__dict__.get('status', 'draft')\n return \"[{0}] {1}\".format(status.upper(), title)\n```\n\n### \ud83c\udf10 Nested DataClass Support\n\n```python\n@dataclass\nclass Address(object):\n street = StringField()\n city = StringField()\n zip_code = StringField()\n\n@dataclass\nclass User(object):\n name = StringField()\n address = Address # Class reference (auto-instantiated)\n addresses = ListField(item_type=Address) # List of nested objects\n```\n\n## Complete Examples\n\n### \ud83d\udcc1 Example Files\n\nThe project provides rich examples in the `examples/` directory:\n\n- **[Basic Usage Example](examples/basic_usage.py)** - Field types, basic dataclass functionality\n- **[Custom Error Messages Example](examples/custom_error_messages.py)** - Multi-language messages, template formatting\n- **[Advanced Features Example](examples/advanced_features.py)** - Custom validation, nested dataclasses, conditional validation\n- **[Real World Examples](examples/real_world_examples.py)** - User management, e-commerce products, blog systems\n\n### \ud83d\ude80 Running Examples\n\n```bash\n# Basic usage example\npython examples/basic_usage.py\n\n# Custom error messages example\npython examples/custom_error_messages.py\n\n# Advanced features example\npython examples/advanced_features.py\n\n# Real world examples\npython examples/real_world_examples.py\n```\n\n### \ud83d\udca1 Quick Example\n\n#### User Management System\n\n```python\nfrom schema_dataclass import StringField, NumberField, ListField, dataclass, validate\n\n@dataclass\nclass User(object):\n username = StringField(\n min_length=3,\n max_length=20,\n regex=r'^[a-zA-Z][a-zA-Z0-9_]*$',\n error_messages={\n 'required': 'Username is required',\n 'min_length': 'Username must be at least {min_length} characters long',\n 'regex': 'Username must start with a letter and contain only letters, numbers, and underscores'\n }\n )\n \n email = StringField(\n regex=r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$',\n error_messages={\n 'required': 'Email address is required',\n 'regex': 'Please enter a valid email address'\n }\n )\n \n age = NumberField(\n minvalue=13,\n maxvalue=120,\n error_messages={\n 'minvalue': 'Age cannot be less than {minvalue}',\n 'maxvalue': 'Age cannot be greater than {maxvalue}'\n }\n )\n \n tags = ListField(\n item_type=str,\n required=False,\n max_length=10,\n error_messages={\n 'max_length': 'Cannot have more than {max_length} tags'\n }\n )\n \n @validate(\"username\")\n def validate_username_not_reserved(self, username):\n \"\"\"Check if username is a reserved word\"\"\"\n reserved = ['admin', 'root', 'system']\n if username.lower() in reserved:\n raise ValidationError(f\"Username '{username}' is a reserved word\")\n\n# Usage example\nuser = User(\n username=\"alice_dev\",\n email=\"alice@example.com\",\n age=28,\n tags=[\"developer\", \"python\"]\n)\n\nprint(\"User: {}\".format(user.username))\nprint(\"Email: {}\".format(user.email))\nprint(\"Age: {}\".format(user.age))\nprint(\"Tags: {}\".format(user.tags))\n```\n\n## API Reference\n\n> **Important Change Notice**: Starting from version 2.0, all fields are optional by default (`required=False`). For required fields, explicitly set `required=True`.\n\n### Field Types\n\n#### StringField\n\n```python\nStringField(\n default=None, # Default value\n alias=None, # Field alias\n required=False, # Whether the field is required (default: False)\n min_length=None, # Minimum length\n max_length=None, # Maximum length\n regex=None, # Regular expression pattern\n choices=None, # Enumeration options\n error_messages=None # Custom error messages\n)\n```\n\n#### NumberField\n\n```python\nNumberField(\n default=None, # Default value\n alias=None, # Field alias\n required=False, # Whether the field is required (default: False)\n minvalue=None, # Minimum value\n maxvalue=None, # Maximum value\n choices=None, # Enumeration options\n error_messages=None # Custom error messages\n)\n```\n\n#### ListField\n\n```python\nListField(\n default=None, # Default value\n alias=None, # Field alias\n required=False, # Whether the field is required (default: False)\n min_length=None, # Minimum length\n max_length=None, # Maximum length\n item_type=None, # Type of list items\n error_messages=None # Custom error messages\n)\n```\n\n### Decorators\n\n#### @dataclass\n\n```python\n@dataclass\nclass MyClass(object):\n field1 = StringField()\n field2 = NumberField()\n```\n\n#### @validate\n\n```python\n@dataclass\nclass MyClass(object):\n field1 = StringField()\n\n @validate(\"field1\")\n def validate_field1(self, value):\n # Custom validation logic\n if not condition:\n raise ValidationError(\"Custom validation failed\")\n```\n\n### Error Message Keys\n\n#### Common Error Message Keys\n\n- `required`: Required field is empty\n- `invalid_type`: Type mismatch\n\n#### StringField Error Message Keys\n\n- `min_length`: Length below minimum\n- `max_length`: Length above maximum\n- `regex`: Regular expression mismatch\n- `choices`: Value not in enumeration options\n\n#### NumberField Error Message Keys\n\n- `minvalue`: Value below minimum\n- `maxvalue`: Value above maximum\n- `choices`: Value not in enumeration options\n\n#### ListField Error Message Keys\n\n- `min_length`: List length below minimum\n- `max_length`: List length above maximum\n- `invalid_list_item`: List item type mismatch\n\n## Validation Features\n\n### String Validation\n\n- Length validation: `min_length`, `max_length`\n- Regular expression validation: `regex`\n- Enumeration validation: `choices`\n- Custom error messages for all validation types\n\n### Number Validation\n\n- Range validation: `minvalue`, `maxvalue`\n- Enumeration validation: `choices`\n- Type validation: automatic support for int, float, long (Python 2)\n- Custom error messages for all validation types\n\n### List Validation\n\n- Length validation: `min_length`, `max_length`\n- Item type validation: `item_type`\n- Supports nesting: strings, numbers, dataclass models\n- Custom error messages for list item type errors\n\n### DataClass Field Support\n\n- Support dataclass as field types\n- Automatic instantiation and validation\n- Re-creation of objects on reassignment\n- Support nested `to_dict()` conversion\n- Validation on reassignment\n\n### Custom Validation\n\n- Use `@validate(\"field_name\")` decorator\n- Executed after basic validation\n- Support multiple custom validation functions\n\n### Custom Error Messages Features\n\n- **Multi-language Support**: Full support for Chinese, English, and other languages\n- **Template Formatting**: Support `{parameter}` style parameter replacement\n- **Complete Coverage**: Support custom error messages for all validation types\n- **Backward Compatibility**: Doesn't affect existing code, optional usage\n- **Robustness**: Graceful degradation when formatting fails, returns original template\n- **Zero Performance Impact**: Same performance as original version when not using custom messages\n\n#### Supported Error Message Types\n\n- **Common**: `required`, `invalid_type`\n- **StringField**: `min_length`, `max_length`, `regex`, `choices`\n- **NumberField**: `minvalue`, `maxvalue`, `choices`\n- **ListField**: `min_length`, `max_length`, `invalid_list_item`\n\n## Testing\n\n### Running Tests\n\n```bash\n# Run all tests\npytest\n\n# Run specific test file\npytest tests/test_fields.py\n\n# Run tests with coverage\npytest --cov=schema_dataclass\n\n# Run tests with specific markers\npytest -m \"unit\"\npytest -m \"integration\"\npytest -m \"error_messages\"\n```\n\n### Test Structure\n\n```\ntests/\n\u251c\u2500\u2500 conftest.py # pytest configuration and fixtures\n\u251c\u2500\u2500 test_fields.py # Field type tests\n\u251c\u2500\u2500 test_custom_error_messages.py # Custom error messages tests\n\u251c\u2500\u2500 test_dataclass.py # dataclass functionality tests\n\u2514\u2500\u2500 test_integration.py # Integration tests\n```\n\n### Test Coverage\n\n- **25+ test cases** covering all functionality\n- **100% test pass rate**\n- **Backward compatibility verification**\n- **Multi-language error message tests**\n- **Complex scenario boundary testing**\n\n## Compatibility\n\n- **Python 2.7+**: Fully supported\n- **Python 3.4+**: Fully supported\n- **PyPy**: Supported\n- **Jython**: Theoretically supported (untested)\n\n## Performance\n\n- **Zero Dependencies**: Uses only Python standard library\n- **Lightweight**: Core code under 1000 lines\n- **High Performance**: Fast validation with low memory usage\n- **Extensible**: Easy to add new field types and validation rules\n\n## Contributing\n\nContributions are welcome! Please follow these steps:\n\n1. Fork the project\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Add test cases\n4. Ensure all tests pass (`pytest`)\n5. Update relevant documentation\n6. Commit your changes (`git commit -m 'Add amazing feature'`)\n7. Push to the branch (`git push origin feature/amazing-feature`)\n8. Create a Pull Request\n\n### Development Environment Setup\n\n```bash\ngit clone https://github.com/schemas/dataclass.git\ncd dataclass\npip install -e .\npip install -r requirements-dev.txt\n```\n\n### Code Guidelines\n\n- Follow PEP 8 coding style\n- Add appropriate docstrings\n- Add test cases for new features\n- Maintain Python 2/3 compatibility\n\n## License\n\nThis project is licensed under the GNU General Public License v3.0. See the [LICENSE](LICENSE) file for details.\n\n## Changelog\n\nCheck [CHANGELOG.md](CHANGELOG.md) for detailed version history and updates.\n\n---\n\n**Note**: This library is fully compatible with Python 2.7 and Python 3.x. Custom error messages are an optional feature that doesn't affect the usage of existing code.\n",
"bugtrack_url": null,
"license": null,
"summary": "Python 2/3 \u517c\u5bb9\u7684 DataClass \u5e93\uff0c\u652f\u6301\u5b8c\u6574\u7684\u6570\u636e\u6821\u9a8c\u529f\u80fd\u548c\u81ea\u5b9a\u4e49\u9519\u8bef\u6d88\u606f",
"version": "0.0.2",
"project_urls": {
"Bug Reports": "https://github.com/b40yd/schemas-python/issues",
"Changelog": "https://github.com/b40yd/schemas-python/blob/main/CHANGELOG.md",
"Documentation": "https://github.com/b40yd/schemas-python/blob/main/README.md",
"Homepage": "https://github.com/b40yd/schemas-python",
"Repository": "https://github.com/b40yd/schemas-python.git"
},
"split_keywords": [
"dataclass",
" fields",
" python2",
" python3",
" schema",
" validation"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "06dd708070068b2fa978d4a6e594ac76ac9b0205b382fb569c234225a2e48f21",
"md5": "d43de7dceb33a7ccb850f4817c6bc8f9",
"sha256": "45e9f9ba5a23d04fef200b396c57302279fe3cdbcaca98362e9989ff7c6a6978"
},
"downloads": -1,
"filename": "schema_dataclass-0.0.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "d43de7dceb33a7ccb850f4817c6bc8f9",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 27070,
"upload_time": "2025-08-24T04:50:39",
"upload_time_iso_8601": "2025-08-24T04:50:39.126407Z",
"url": "https://files.pythonhosted.org/packages/06/dd/708070068b2fa978d4a6e594ac76ac9b0205b382fb569c234225a2e48f21/schema_dataclass-0.0.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "635104ce2a6f532d694a8b5810ef31c1709a866f753a97675318e6d7054ebcf6",
"md5": "eb7855941282842edf292b4d88abd6b1",
"sha256": "b54734eca91d25475f93e3fcb9fea842fffa8b923e73cbe3baf2f2e4d262e02e"
},
"downloads": -1,
"filename": "schema_dataclass-0.0.2.tar.gz",
"has_sig": false,
"md5_digest": "eb7855941282842edf292b4d88abd6b1",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 55536,
"upload_time": "2025-08-24T04:50:40",
"upload_time_iso_8601": "2025-08-24T04:50:40.721539Z",
"url": "https://files.pythonhosted.org/packages/63/51/04ce2a6f532d694a8b5810ef31c1709a866f753a97675318e6d7054ebcf6/schema_dataclass-0.0.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-24 04:50:40",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "b40yd",
"github_project": "schemas-python",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [],
"lcname": "schema-dataclass"
}