dataclass-csv

1.4.1 · active · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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}")

view raw JSON →