Registry / serialization / dataclass-csv

dataclass-csv

JSON →
library1.4.1pypypi✓ verified 86d ago

dataclass-csv is a Python library designed to effortlessly map CSV data into Python dataclasses. It handles type conversions automatically for standard types and supports custom converters for more complex scenarios. The library provides both a reader and a writer for CSV operations with dataclasses. It is currently at version 1.4.1 and sees active development with a moderate release cadence, addressing issues and adding features.

pip install dataclass-csv
INSTALL
IMPORT
SIG · DATACLASS-CSV
D
dataclass-csv
serializationpythonv1.4.1
Install
1.5s avg
Import
41ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.4.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.915 runs
installs and imports cleanly · install 0.0s · import 0.044s · 17.9MB
glibc
py 3.103.915 runs
installs and imports cleanly · install 1.5s · import 0.038s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

DataclassReader
from dataclass_csv import DataclassReader
DataclassWriter
from dataclass_csv import DataclassWriter

Demonstrates how to define a dataclass, prepare CSV data, and use `DataclassReader` to parse the CSV into a list of dataclass objects, handling automatic type conversion for int, float, and bool.

import dataclasses from dataclass_csv import DataclassReader import io @dataclasses.dataclass class Product: product_id: int name: str price: float in_stock: bool csv_data = """product_id,name,price,in_stock 101,Laptop,1200.50,true 102,Mouse,25.99,False 103,Keyboard,75.00,1 104,Monitor,300.00,0 """ # Read CSV data into dataclass instances reader = DataclassReader(io.StringIO(csv_data), Product) products = [] for product in reader: products.append(product) print(f"Product: {product.name}, Price: ${product.price}, In Stock: {product.in_stock}") # Example of accessing a specific product if products: print(f"\nFirst product name: {products[0].name}")
Debug
Known issues
breakingStarting from version 1.4.1, the internal boolean string conversion logic has changed. Previously, it used `distutils.util.strtobool` which raised a `ValueError` for unrecognized boolean strings (e.g., 'unknown'). The new implementation converts unrecognized strings to `False` instead of raising an error. This can silently change behavior if your CSV contains non-standard boolean representations.
fix
Review your CSV data for non-standard boolean strings (other than 'true', '1', 'yes', 'y', 'on' for True; or 'false', '0', 'no', 'n', 'off' for False). If your application relied on `ValueError` being raised for invalid boolean values, you'll need to add custom validation or a custom converter to replicate that behavior.
affects: >=1.4.1
gotchaBefore version 1.3.0, if your CSV file contained duplicated header names, `dataclass-csv` might have silently mapped data incorrectly or overwritten values. From 1.3.0 onwards, it explicitly checks for and raises a `DuplicatedHeaderError` for such cases.
fix
Always ensure your CSV files have unique column headers. If you encounter `DuplicatedHeaderError`, rename duplicate columns in your CSV, or use `dataclasses.field(metadata={'dataclass_csv': {'column_name': '...'}})` for explicit mapping if you absolutely need to handle ambiguous columns (though this is not recommended).
affects: <1.3.0
gotchaAutomatic date and datetime type conversion was officially introduced in version 1.4.0. Prior versions did not inherently support converting string representations of dates (e.g., 'YYYY-MM-DD') into `datetime.date` or `datetime.datetime` objects, requiring manual conversion or custom type converters.
fix
For versions older than 1.4.0, use a custom `TypeConverter` to handle date/datetime fields. For versions 1.4.0+, ensure your date strings are in standard formats parseable by Python's `datetime` module, or specify a format string via `dataclasses.field(metadata={'dataclass_csv': {'date_format': '%Y-%m-%d'}})`.
affects: <1.4.0
deprecatedThe project deprecated `pipenv` for dependency management in version 1.4.1, moving towards `poetry`. While this primarily affects project contributors and development setup, users following older contribution guides or examples might find inconsistencies.
fix
For new development environments or contributions, consult the latest `pyproject.toml` and README on GitHub for the recommended dependency management tool (currently `poetry`). If you're only using the library as a dependency, this change does not affect your application.
affects: >=1.4.1
Errors
Common errors & fixes
dataclass_csv.exceptions.DuplicatedHeaderError: CSV header '...' is duplicated. This can lead to unexpected data mapping.
Your CSV file contains multiple columns with the same header name, which dataclass-csv considers ambiguous and prevents to ensure data integrity.
fix
Modify your CSV file to ensure all header names are unique. If you have columns with logically similar data, give them distinct names (e.g., `value_1`, `value_2`).
ValueError: invalid literal for int() with base 10: 'abc' (or similar for float, date, bool)
A value in your CSV column could not be automatically converted to the type specified in the corresponding dataclass field (e.g., a string 'abc' into an `int`).
fix
Inspect the CSV data and the dataclass field type. Ensure the data matches the type, or provide a custom `TypeConverter` (via `DataclassReader(..., converter=...)`) if you need special handling for conversions or errors.
AttributeError: type object 'MyDataclass' has no attribute 'missing_field'
This error typically occurs when trying to access a field on your dataclass instance that either does not exist in the dataclass definition or was not mapped from the CSV (e.g., a CSV header name did not match a dataclass field name).
fix
Verify that your CSV header names exactly match the field names in your dataclass (case-sensitive). If the names differ, use `dataclasses.field(metadata={'dataclass_csv': {'column_name': 'ActualCsvHeader'}})` to explicitly map them.
Upgrade
Version history
1.4.1latest on PyPI · released Feb 1, 2026
Audit
Dependencies

No dependency data recorded yet.

Agent activity
9 hits · last 30 days
node
8
OpenAI (training)
1
Resources
dataclass-csv — pip install dataclass-csv · libregistry